From 47cd54de229f32394766e28ffe7203b99d3f6bdf Mon Sep 17 00:00:00 2001 From: Cody Date: Tue, 15 Dec 2015 18:51:17 +0000 Subject: [PATCH 1/2] Migrated `%` string formating --- package/MDAnalysis/analysis/align.py | 11 +- package/MDAnalysis/analysis/contacts.py | 17 ++- package/MDAnalysis/analysis/density.py | 20 +-- .../analysis/hbonds/hbond_analysis.py | 31 ++--- package/MDAnalysis/analysis/helanal.py | 38 +++--- package/MDAnalysis/analysis/hole.py | 8 +- package/MDAnalysis/analysis/leaflet.py | 7 +- package/MDAnalysis/analysis/nuclinfo.py | 128 +++++++++--------- package/MDAnalysis/analysis/rms.py | 14 +- package/MDAnalysis/analysis/x3dna.py | 14 +- package/MDAnalysis/coordinates/LAMMPS.py | 8 +- package/MDAnalysis/coordinates/PDB.py | 11 +- package/MDAnalysis/coordinates/PDBQT.py | 3 +- package/MDAnalysis/coordinates/TRJ.py | 4 +- package/MDAnalysis/coordinates/XYZ.py | 2 +- package/MDAnalysis/coordinates/base.py | 14 +- package/MDAnalysis/coordinates/core.py | 8 +- .../MDAnalysis/coordinates/pdb/extensions.py | 5 +- .../MDAnalysis/coordinates/xdrfile/core.py | 2 +- .../coordinates/xdrfile/libxdrfile2.py | 4 +- .../coordinates/xdrfile/src/libxdrfile2.py | 4 +- package/MDAnalysis/core/AtomGroup.py | 10 +- package/MDAnalysis/core/Selection.py | 6 +- package/MDAnalysis/core/Timeseries.py | 10 +- package/MDAnalysis/core/__init__.py | 2 +- package/MDAnalysis/lib/transformations.py | 2 +- package/MDAnalysis/lib/util.py | 14 +- package/MDAnalysis/selections/__init__.py | 3 +- package/MDAnalysis/selections/base.py | 4 +- package/MDAnalysis/selections/charmm.py | 4 +- package/MDAnalysis/selections/gromacs.py | 2 +- package/MDAnalysis/selections/jmol.py | 2 +- package/MDAnalysis/selections/pymol.py | 4 +- package/MDAnalysis/selections/vmd.py | 2 +- package/examples/amber2dcd.py | 6 +- package/examples/backbone_dihedral.py | 2 +- package/examples/blocks.py | 2 +- package/examples/dcd2xtc.py | 4 +- package/examples/lipid_order_parameters.py | 4 +- package/examples/membrane-composition.py | 12 +- package/examples/membrane-leaflets.py | 6 +- package/examples/membrane-parameters.py | 8 +- package/examples/multimers-analysis.py | 6 +- package/examples/nativecontacts.py | 2 +- .../examples/radial_distribution_function.py | 8 +- package/examples/rmsd.py | 8 +- package/examples/schlitter_quasiharmonic.py | 2 +- package/setup.py | 8 +- .../MDAnalysisTests/analysis/test_align.py | 2 +- testsuite/MDAnalysisTests/coordinates/base.py | 2 +- .../coordinates/test_coordinates.py | 7 +- .../MDAnalysisTests/coordinates/test_dcd.py | 16 +-- .../MDAnalysisTests/coordinates/test_trz.py | 2 +- .../MDAnalysisTests/coordinates/test_xdr.py | 6 +- testsuite/MDAnalysisTests/test_atomgroup.py | 2 +- testsuite/ez_setup.py | 7 +- testsuite/setup.py | 6 +- 57 files changed, 263 insertions(+), 283 deletions(-) diff --git a/package/MDAnalysis/analysis/align.py b/package/MDAnalysis/analysis/align.py index 96d275bfcf0..66eecb277c0 100644 --- a/package/MDAnalysis/analysis/align.py +++ b/package/MDAnalysis/analysis/align.py @@ -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() @@ -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: @@ -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:4!s} {1:3d} {2:3!s} {3:3!s} {4:6.3f} | {5:4!s} {6:3d} {7:3!s} {8:3!s} {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) diff --git a/package/MDAnalysis/analysis/contacts.py b/package/MDAnalysis/analysis/contacts.py index 910e5e5daad..a3b0092bbd4 100644 --- a/package/MDAnalysis/analysis/contacts.py +++ b/package/MDAnalysis/analysis/contacts.py @@ -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 @@ -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: @@ -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: @@ -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: @@ -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 @@ -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]) @@ -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() diff --git a/package/MDAnalysis/analysis/density.py b/package/MDAnalysis/analysis/density.py index 32b3faf228a..a280d8a915c 100644 --- a/package/MDAnalysis/analysis/density.py +++ b/package/MDAnalysis/analysis/density.py @@ -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): @@ -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 @@ -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 @@ -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 @@ -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) @@ -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): @@ -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): diff --git a/package/MDAnalysis/analysis/hbonds/hbond_analysis.py b/package/MDAnalysis/analysis/hbonds/hbond_analysis.py index dffc0d47b96..4aa8333b7a9 100644 --- a/package/MDAnalysis/analysis/hbonds/hbond_analysis.py +++ b/package/MDAnalysis/analysis/hbonds/hbond_analysis.py @@ -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 @@ -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 @@ -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 [] @@ -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: @@ -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") @@ -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", diff --git a/package/MDAnalysis/analysis/helanal.py b/package/MDAnalysis/analysis/helanal.py index 90c6c12e9b1..7712849c688 100644 --- a/package/MDAnalysis/analysis/helanal.py +++ b/package/MDAnalysis/analysis/helanal.py @@ -263,7 +263,7 @@ def helanal_trajectory(universe, selection="name CA", start=None, end=None, begi start = universe.atoms[0].resid if end is None: end = universe.atoms[-1].resid - selection += " and resid %(start)d:%(end)d" % vars() + selection += " and resid {start:d}:{end:d}".format(**vars()) ca = universe.select_atoms(selection) trajectory = universe.trajectory @@ -280,7 +280,7 @@ def helanal_trajectory(universe, selection="name CA", start=None, end=None, begi print "Analysing from residue", start, "to the C termini" elif start is None and end is not None: print "Analysing from the N termini to", end - print "Analysing %d/%d residues" % (ca.n_atoms, universe.atoms.n_residues) + print "Analysing {0:d}/{1:d} residues".format(ca.n_atoms, universe.atoms.n_residues) if not prefix is None: prefix = str(prefix) @@ -379,9 +379,9 @@ def helanal_trajectory(universe, selection="name CA", start=None, end=None, begi #for store,tmp in zip(global_tilt,local_helix_axes): store.append(vecangle(tmp,ref_axis)) #simple ticker - formated_time = "%20.1f" % trajectory.time + formated_time = "{0:20.1f}".format(trajectory.time) frame += 1 - formated_frame = "%10d" % frame + formated_frame = "{0:10d}".format(frame) print '\r', formated_time, ' ps', formated_frame, @@ -401,21 +401,21 @@ def helanal_trajectory(universe, selection="name CA", start=None, end=None, begi print >> mat_output, "Mean" for row in bending_statistics_matrix: for col in row: - formatted_angle = "%6.1f" % col[0] + formatted_angle = "{0:6.1f}".format(col[0]) print >> mat_output, formatted_angle, print >> mat_output, '' print >> mat_output, "\nSD" for row in bending_statistics_matrix: for col in row: - formatted_angle = "%6.1f" % col[1] + formatted_angle = "{0:6.1f}".format(col[1]) print >> mat_output, formatted_angle, print >> mat_output, '' print >> mat_output, "\nABDEV" for row in bending_statistics_matrix: for col in row: - formatted_angle = "%6.1f" % col[2] + formatted_angle = "{0:6.1f}".format(col[2]) print >> mat_output, formatted_angle, print >> mat_output, '' @@ -429,17 +429,17 @@ def helanal_trajectory(universe, selection="name CA", start=None, end=None, begi print "ResID", if start is None: for item in range(4, len(residue_statistics[0]) + 4): - output = "%8d" % item + output = "{0:8d}".format(item) print output, else: for item in range(start + 3, len(residue_statistics[0]) + start + 3): - output = "%8d" % item + output = "{0:8d}".format(item) print output, print "" for measure, name in zip(residue_statistics, measure_names): print name, for residue in measure: - output = "%8.1f" % residue + output = "{0:8.1f}".format(residue) print output, print '' @@ -453,18 +453,18 @@ def helanal_trajectory(universe, selection="name CA", start=None, end=None, begi print >> summary_output, "ResID", if start is None: for item in range(4, len(residue_statistics[0]) + 4): - output = "%8d" % item + output = "{0:8d}".format(item) print >> summary_output, output, else: for item in range(start + 3, len(residue_statistics[0]) + start + 3): - output = "%8d" % item + output = "{0:8d}".format(item) print >> summary_output, output, print >> summary_output, "" for measure, name in zip(residue_statistics, measure_names): print >> summary_output, name, for residue in measure: - output = "%8.1f" % residue + output = "{0:8.1f}".format(residue) print >> summary_output, output, print >> summary_output, '' @@ -521,9 +521,9 @@ def helanal_main(pdbfile, selection="name CA", start=None, end=None, ref_axis=No start = universe.atoms[0].resid if end is None: end = universe.atoms[-1].resid - selection += " and resid %(start)d:%(end)d" % vars() + selection += " and resid {start:d}:{end:d}".format(**vars()) ca = universe.select_atoms(selection) - print "Analysing %d/%d residues" % (ca.n_atoms, universe.atoms.n_residues) + print "Analysing {0:d}/{1:d} residues".format(ca.n_atoms, universe.atoms.n_residues) twist, bending_angles, height, rnou, origins, local_helix_axes, local_screw_angles = \ main_loop(ca.coordinates(), ref_axis=ref_axis) @@ -548,7 +548,7 @@ def helanal_main(pdbfile, selection="name CA", start=None, end=None, ref_axis=No angle = 0. else: angle = np.rad2deg(np.arccos(vecscaler(i, j))) - string_angle = "%6.0f\t" % angle + string_angle = "{0:6.0f}\t".format(angle) #print string_angle, #print '' #TESTED- local bending matrix! @@ -575,12 +575,12 @@ def helanal_main(pdbfile, selection="name CA", start=None, end=None, ref_axis=No #print mean_height, sd_height, abdev_height print "Local bending angles:" for angle in bending_angles: - output = "%8.1f\t" % angle + output = "{0:8.1f}\t".format(angle) print output, print '' print "Unit twist angles:" for twist_ang in twist: - outputtwist = "%8.1f\t" % twist_ang + outputtwist = "{0:8.1f}\t".format(twist_ang) print outputtwist, print '' @@ -601,7 +601,7 @@ def origin_pdb(origins, pdbfile): with open(pdbfile, 'a') as output: i = 1 for xyz in origins: - tmp = "ATOM %3d CA ALA %3d %8.3f%8.3f%8.3f 1.00 0.00" % (i, i, xyz[0], xyz[1], xyz[2]) + tmp = "ATOM {0:3d} CA ALA {1:3d} {2:8.3f}{3:8.3f}{4:8.3f} 1.00 0.00".format(i, i, xyz[0], xyz[1], xyz[2]) print >> output, tmp i += 1 print >> output, "TER\nENDMDL" diff --git a/package/MDAnalysis/analysis/hole.py b/package/MDAnalysis/analysis/hole.py index 55f5d158fb7..5c450113f71 100644 --- a/package/MDAnalysis/analysis/hole.py +++ b/package/MDAnalysis/analysis/hole.py @@ -696,7 +696,7 @@ def __init__(self, filename, **kwargs): hole_exe_name = kwargs.pop('executable', 'hole') self.exe['hole'] = which(hole_exe_name) if self.exe['hole'] is None: - errmsg = "HOLE binary %(hole_exe_name)r not found." % vars() + errmsg = "HOLE binary {hole_exe_name!r} not found.".format(**vars()) logger.fatal(errmsg) logger.fatal("%(hole_exe_name)r must be on the PATH or provided as keyword argument 'executable'.", vars()) @@ -823,7 +823,7 @@ def run(self, **kwargs): logger.fatal("HOLE Failure (%d). Check output %r", hole.returncode, outname) if stderr is not None: logger.fatal(stderr) - raise ApplicationError(hole.returncode, "HOLE %r failed. Check output %r." % (self.exe['hole'], outname)) + raise ApplicationError(hole.returncode, "HOLE {0!r} failed. Check output {1!r}.".format(self.exe['hole'], outname)) logger.info("HOLE finished: output file %(outname)r", vars()) def create_vmd_surface(self, filename="hole.vmd", **kwargs): @@ -920,7 +920,7 @@ def collect(self, **kwargs): length = len(filenames) if length == 0: logger.error("Glob pattern %r did not find any files.", self.filename) - raise ValueError("Glob pattern %r did not find any files." % (self.filename,)) + raise ValueError("Glob pattern {0!r} did not find any files.".format(self.filename)) logger.info("Found %d input files based on glob pattern %s", length, self.filename) if self.dcd: from MDAnalysis import Universe @@ -975,7 +975,7 @@ def collect(self, **kwargs): rundir = os.path.join(outdir, "run_" + str(run)) if not os.path.exists(rundir): os.makedirs(rundir) - frame_hole_txt = os.path.join(rundir, "radii_%s_%04d.dat.gz" % (run, hole_profile_no)) + frame_hole_txt = os.path.join(rundir, "radii_{0!s}_{1:04d}.dat.gz".format(run, hole_profile_no)) np.savetxt(frame_hole_txt, frame_hole_output) logger.debug("Finished with frame %d, saved as %r", hole_profile_no, frame_hole_txt) continue diff --git a/package/MDAnalysis/analysis/leaflet.py b/package/MDAnalysis/analysis/leaflet.py index 8769da7e146..1ea202f2385 100644 --- a/package/MDAnalysis/analysis/leaflet.py +++ b/package/MDAnalysis/analysis/leaflet.py @@ -209,15 +209,14 @@ def write_selection(self, filename, **kwargs): SelectionWriter = MDAnalysis.selections.get_writer(filename, kwargs.pop('format', None)) writer = SelectionWriter( filename, mode=kwargs.pop('mode', 'wa'), - preamble="leaflets based on selection=%(selectionstring)r cutoff=%(cutoff)f\n" % vars(self), + preamble="leaflets based on selection={selectionstring!r} cutoff={cutoff:f}\n".format(**vars(self)), **kwargs) for i, ag in enumerate(self.groups_iter()): - name = "leaflet_%d" % (i + 1) + name = "leaflet_{0:d}".format((i + 1)) writer.write(ag, name=name) def __repr__(self): - return "" % \ - (self.selectionstring, self.cutoff, self.selection.n_atoms, + return "".format(self.selectionstring, self.cutoff, self.selection.n_atoms, len(self.components)) diff --git a/package/MDAnalysis/analysis/nuclinfo.py b/package/MDAnalysis/analysis/nuclinfo.py index 13801fe3c46..77519dfda5c 100644 --- a/package/MDAnalysis/analysis/nuclinfo.py +++ b/package/MDAnalysis/analysis/nuclinfo.py @@ -127,12 +127,12 @@ def wc_pair(universe, i, bp, seg1="SYSTEM", seg2="SYSTEM"): .. versionadded:: 0.7.6 """ - if universe.select_atoms(" resid %s " % (i,)).resnames[0] in ["DC", "DT", "U", "C", "T", "CYT", "THY", "URA"]: + if universe.select_atoms(" resid {0!s} ".format(i)).resnames[0] in ["DC", "DT", "U", "C", "T", "CYT", "THY", "URA"]: a1, a2 = "N3", "N1" - if universe.select_atoms(" resid %s " % (i,)).resnames[0] in ["DG", "DA", "A", "G", "ADE", "GUA"]: + if universe.select_atoms(" resid {0!s} ".format(i)).resnames[0] in ["DG", "DA", "A", "G", "ADE", "GUA"]: a1, a2 = "N1", "N3" wc_dist = universe.select_atoms( - " (segid %s and resid %s and name %s) or (segid %s and resid %s and name %s) " % (seg1, i, a1, seg2, bp, a2)) + " (segid {0!s} and resid {1!s} and name {2!s}) or (segid {3!s} and resid {4!s} and name {5!s}) ".format(seg1, i, a1, seg2, bp, a2)) wc = mdamath.norm(wc_dist[0].pos - wc_dist[1].pos) return wc @@ -159,12 +159,12 @@ def minor_pair(universe, i, bp, seg1="SYSTEM", seg2="SYSTEM"): .. versionadded:: 0.7.6 """ - if universe.select_atoms(" resid %s " % (i,)).resnames[0] in ["DC", "DT", "U", "C", "T", "CYT", "THY", "URA"]: + if universe.select_atoms(" resid {0!s} ".format(i)).resnames[0] in ["DC", "DT", "U", "C", "T", "CYT", "THY", "URA"]: a1, a2 = "O2", "C2" - if universe.select_atoms(" resid %s " % (i,)).resnames[0] in ["DG", "DA", "A", "G", "ADE", "GUA"]: + if universe.select_atoms(" resid {0!s} ".format(i)).resnames[0] in ["DG", "DA", "A", "G", "ADE", "GUA"]: a1, a2 = "C2", "O2" c2o2_dist = universe.select_atoms( - " (segid %s and resid %s and name %s) or (segid %s and resid %s and name %s) " % (seg1, i, a1, seg2, bp, a2)) + " (segid {0!s} and resid {1!s} and name {2!s}) or (segid {3!s} and resid {4!s} and name {5!s}) ".format(seg1, i, a1, seg2, bp, a2)) c2o2 = mdamath.norm(c2o2_dist[0].pos - c2o2_dist[1].pos) return c2o2 @@ -191,18 +191,18 @@ def major_pair(universe, i, bp, seg1="SYSTEM", seg2="SYSTEM"): .. versionadded:: 0.7.6 """ - if universe.select_atoms(" resid %s " % (i,)).resnames[0] in ["DC", "DG", "C", "G", "CYT", "GUA"]: - if universe.select_atoms(" resid %s " % (i,)).resnames[0] in ["DC", "C", "CYT"]: + if universe.select_atoms(" resid {0!s} ".format(i)).resnames[0] in ["DC", "DG", "C", "G", "CYT", "GUA"]: + if universe.select_atoms(" resid {0!s} ".format(i)).resnames[0] in ["DC", "C", "CYT"]: a1, a2 = "N4", "O6" else: a1, a2 = "O6", "N4" - if universe.select_atoms(" resid %s " % (i,)).resnames[0] in ["DT", "DA", "A", "T", "U", "ADE", "THY", "URA"]: - if universe.select_atoms(" resid %s " % (i,)).resnames[0] in ["DT", "T", "THY", "U", "URA"]: + if universe.select_atoms(" resid {0!s} ".format(i)).resnames[0] in ["DT", "DA", "A", "T", "U", "ADE", "THY", "URA"]: + if universe.select_atoms(" resid {0!s} ".format(i)).resnames[0] in ["DT", "T", "THY", "U", "URA"]: a1, a2 = "O4", "N6" else: a1, a2 = "N6", "O4" no_dist = universe.select_atoms( - " (segid %s and resid %s and name %s) or (segid %s and resid %s and name %s) " % (seg1, i, a1, seg2, bp, a2)) + " (segid {0!s} and resid {1!s} and name {2!s}) or (segid {3!s} and resid {4!s} and name {5!s}) ".format(seg1, i, a1, seg2, bp, a2)) major = mdamath.norm(no_dist[0].pos - no_dist[1].pos) return major @@ -223,11 +223,11 @@ def phase_cp(universe, seg, i): .. versionadded:: 0.7.6 """ - atom1 = universe.select_atoms(" atom %s %s O4\' " % (seg, i)) - atom2 = universe.select_atoms(" atom %s %s C1\' " % (seg, i)) - atom3 = universe.select_atoms(" atom %s %s C2\' " % (seg, i)) - atom4 = universe.select_atoms(" atom %s %s C3\' " % (seg, i)) - atom5 = universe.select_atoms(" atom %s %s C4\' " % (seg, i)) + atom1 = universe.select_atoms(" atom {0!s} {1!s} O4\' ".format(seg, i)) + atom2 = universe.select_atoms(" atom {0!s} {1!s} C1\' ".format(seg, i)) + atom3 = universe.select_atoms(" atom {0!s} {1!s} C2\' ".format(seg, i)) + atom4 = universe.select_atoms(" atom {0!s} {1!s} C3\' ".format(seg, i)) + atom5 = universe.select_atoms(" atom {0!s} {1!s} C4\' ".format(seg, i)) data1 = atom1.coordinates() data2 = atom2.coordinates() @@ -287,16 +287,16 @@ def phase_as(universe, seg, i): .. versionadded:: 0.7.6 """ - angle1 = universe.select_atoms(" atom %s %s C1\' " % (seg, i), " atom %s %s C2\' " % (seg, i), - " atom %s %s C3\' " % (seg, i), " atom %s %s C4\' " % (seg, i)) - angle2 = universe.select_atoms(" atom %s %s C2\' " % (seg, i), " atom %s %s C3\' " % (seg, i), - " atom %s %s C4\' " % (seg, i), " atom %s %s O4\' " % (seg, i)) - angle3 = universe.select_atoms(" atom %s %s C3\' " % (seg, i), " atom %s %s C4\' " % (seg, i), - " atom %s %s O4\' " % (seg, i), " atom %s %s C1\' " % (seg, i)) - angle4 = universe.select_atoms(" atom %s %s C4\' " % (seg, i), " atom %s %s O4\' " % (seg, i), - " atom %s %s C1\' " % (seg, i), " atom %s %s C2\' " % (seg, i)) - angle5 = universe.select_atoms(" atom %s %s O4\' " % (seg, i), " atom %s %s C1\' " % (seg, i), - " atom %s %s C2\' " % (seg, i), " atom %s %s C3\' " % (seg, i)) + angle1 = universe.select_atoms(" atom {0!s} {1!s} C1\' ".format(seg, i), " atom {0!s} {1!s} C2\' ".format(seg, i), + " atom {0!s} {1!s} C3\' ".format(seg, i), " atom {0!s} {1!s} C4\' ".format(seg, i)) + angle2 = universe.select_atoms(" atom {0!s} {1!s} C2\' ".format(seg, i), " atom {0!s} {1!s} C3\' ".format(seg, i), + " atom {0!s} {1!s} C4\' ".format(seg, i), " atom {0!s} {1!s} O4\' ".format(seg, i)) + angle3 = universe.select_atoms(" atom {0!s} {1!s} C3\' ".format(seg, i), " atom {0!s} {1!s} C4\' ".format(seg, i), + " atom {0!s} {1!s} O4\' ".format(seg, i), " atom {0!s} {1!s} C1\' ".format(seg, i)) + angle4 = universe.select_atoms(" atom {0!s} {1!s} C4\' ".format(seg, i), " atom {0!s} {1!s} O4\' ".format(seg, i), + " atom {0!s} {1!s} C1\' ".format(seg, i), " atom {0!s} {1!s} C2\' ".format(seg, i)) + angle5 = universe.select_atoms(" atom {0!s} {1!s} O4\' ".format(seg, i), " atom {0!s} {1!s} C1\' ".format(seg, i), + " atom {0!s} {1!s} C2\' ".format(seg, i), " atom {0!s} {1!s} C3\' ".format(seg, i)) data1 = angle1.dihedral.value() data2 = angle2.dihedral.value() @@ -336,24 +336,24 @@ def tors(universe, seg, i): .. NOTE:: If failure occurs be sure to check the segment identification """ - a = universe.select_atoms(" atom %s %s O3\' " % (seg, i - 1), " atom %s %s P " % (seg, i), - " atom %s %s O5\' " % (seg, i), " atom %s %s C5\' " % (seg, i)) - b = universe.select_atoms(" atom %s %s P " % (seg, i), " atom %s %s O5\' " % (seg, i), - " atom %s %s C5\' " % (seg, i), " atom %s %s C4\' " % (seg, i)) - g = universe.select_atoms(" atom %s %s O5\' " % (seg, i), " atom %s %s C5\' " % (seg, i), - " atom %s %s C4\' " % (seg, i), " atom %s %s C3\' " % (seg, i)) - d = universe.select_atoms(" atom %s %s C5\' " % (seg, i), " atom %s %s C4\' " % (seg, i), - " atom %s %s C3\' " % (seg, i), " atom %s %s O3\' " % (seg, i)) - e = universe.select_atoms(" atom %s %s C4\' " % (seg, i), " atom %s %s C3\' " % (seg, i), - " atom %s %s O3\' " % (seg, i), " atom %s %s P " % (seg, i + 1)) - z = universe.select_atoms(" atom %s %s C3\' " % (seg, i), " atom %s %s O3\' " % (seg, i), - " atom %s %s P " % (seg, i + 1), " atom %s %s O5\' " % (seg, i + 1)) + a = universe.select_atoms(" atom {0!s} {1!s} O3\' ".format(seg, i - 1), " atom {0!s} {1!s} P ".format(seg, i), + " atom {0!s} {1!s} O5\' ".format(seg, i), " atom {0!s} {1!s} C5\' ".format(seg, i)) + b = universe.select_atoms(" atom {0!s} {1!s} P ".format(seg, i), " atom {0!s} {1!s} O5\' ".format(seg, i), + " atom {0!s} {1!s} C5\' ".format(seg, i), " atom {0!s} {1!s} C4\' ".format(seg, i)) + g = universe.select_atoms(" atom {0!s} {1!s} O5\' ".format(seg, i), " atom {0!s} {1!s} C5\' ".format(seg, i), + " atom {0!s} {1!s} C4\' ".format(seg, i), " atom {0!s} {1!s} C3\' ".format(seg, i)) + d = universe.select_atoms(" atom {0!s} {1!s} C5\' ".format(seg, i), " atom {0!s} {1!s} C4\' ".format(seg, i), + " atom {0!s} {1!s} C3\' ".format(seg, i), " atom {0!s} {1!s} O3\' ".format(seg, i)) + e = universe.select_atoms(" atom {0!s} {1!s} C4\' ".format(seg, i), " atom {0!s} {1!s} C3\' ".format(seg, i), + " atom {0!s} {1!s} O3\' ".format(seg, i), " atom {0!s} {1!s} P ".format(seg, i + 1)) + z = universe.select_atoms(" atom {0!s} {1!s} C3\' ".format(seg, i), " atom {0!s} {1!s} O3\' ".format(seg, i), + " atom {0!s} {1!s} P ".format(seg, i + 1), " atom {0!s} {1!s} O5\' ".format(seg, i + 1)) try: - c = universe.select_atoms(" atom %s %s O4\' " % (seg, i), " atom %s %s C1\' " % (seg, i), - " atom %s %s N1 " % (seg, i), " atom %s %s C2 " % (seg, i)) + c = universe.select_atoms(" atom {0!s} {1!s} O4\' ".format(seg, i), " atom {0!s} {1!s} C1\' ".format(seg, i), + " atom {0!s} {1!s} N1 ".format(seg, i), " atom {0!s} {1!s} C2 ".format(seg, i)) except: - c = universe.select_atoms(" atom %s %s O4\' " % (seg, i), " atom %s %s C1\' " % (seg, i), - " atom %s %s N9 " % (seg, i), " atom %s %s C4 " % (seg, i)) + c = universe.select_atoms(" atom {0!s} {1!s} O4\' ".format(seg, i), " atom {0!s} {1!s} C1\' ".format(seg, i), + " atom {0!s} {1!s} N9 ".format(seg, i), " atom {0!s} {1!s} C4 ".format(seg, i)) alpha = a.dihedral.value() beta = b.dihedral.value() @@ -393,8 +393,8 @@ def tors_alpha(universe, seg, i): .. versionadded:: 0.7.6 """ - a = universe.select_atoms(" atom %s %s O3\' " % (seg, i - 1), " atom %s %s P " % (seg, i), - " atom %s %s O5\' " % (seg, i), " atom %s %s C5\' " % (seg, i)) + a = universe.select_atoms(" atom {0!s} {1!s} O3\' ".format(seg, i - 1), " atom {0!s} {1!s} P ".format(seg, i), + " atom {0!s} {1!s} O5\' ".format(seg, i), " atom {0!s} {1!s} C5\' ".format(seg, i)) alpha = a.dihedral.value() if alpha < 0: alpha = alpha + 360 @@ -416,8 +416,8 @@ def tors_beta(universe, seg, i): .. versionadded:: 0.7.6 """ - b = universe.select_atoms(" atom %s %s P " % (seg, i), " atom %s %s O5\' " % (seg, i), - " atom %s %s C5\' " % (seg, i), " atom %s %s C4\' " % (seg, i)) + b = universe.select_atoms(" atom {0!s} {1!s} P ".format(seg, i), " atom {0!s} {1!s} O5\' ".format(seg, i), + " atom {0!s} {1!s} C5\' ".format(seg, i), " atom {0!s} {1!s} C4\' ".format(seg, i)) beta = b.dihedral.value() if beta < 0: beta = beta + 360 @@ -439,8 +439,8 @@ def tors_gamma(universe, seg, i): .. versionadded:: 0.7.6 """ - g = universe.select_atoms(" atom %s %s O5\' " % (seg, i), " atom %s %s C5\' " % (seg, i), - " atom %s %s C4\' " % (seg, i), " atom %s %s C3\' " % (seg, i)) + g = universe.select_atoms(" atom {0!s} {1!s} O5\' ".format(seg, i), " atom {0!s} {1!s} C5\' ".format(seg, i), + " atom {0!s} {1!s} C4\' ".format(seg, i), " atom {0!s} {1!s} C3\' ".format(seg, i)) gamma = g.dihedral.value() if gamma < 0: gamma = gamma + 360 @@ -462,8 +462,8 @@ def tors_delta(universe, seg, i): .. versionadded:: 0.7.6 """ - d = universe.select_atoms(" atom %s %s C5\' " % (seg, i), " atom %s %s C4\' " % (seg, i), - " atom %s %s C3\' " % (seg, i), " atom %s %s O3\' " % (seg, i)) + d = universe.select_atoms(" atom {0!s} {1!s} C5\' ".format(seg, i), " atom {0!s} {1!s} C4\' ".format(seg, i), + " atom {0!s} {1!s} C3\' ".format(seg, i), " atom {0!s} {1!s} O3\' ".format(seg, i)) delta = d.dihedral.value() if delta < 0: delta = delta + 360 @@ -485,8 +485,8 @@ def tors_eps(universe, seg, i): .. versionadded:: 0.7.6 """ - e = universe.select_atoms(" atom %s %s C4\' " % (seg, i), " atom %s %s C3\' " % (seg, i), - " atom %s %s O3\' " % (seg, i), " atom %s %s P " % (seg, i + 1)) + e = universe.select_atoms(" atom {0!s} {1!s} C4\' ".format(seg, i), " atom {0!s} {1!s} C3\' ".format(seg, i), + " atom {0!s} {1!s} O3\' ".format(seg, i), " atom {0!s} {1!s} P ".format(seg, i + 1)) epsilon = e.dihedral.value() if epsilon < 0: epsilon = epsilon + 360 @@ -508,8 +508,8 @@ def tors_zeta(universe, seg, i): .. versionadded:: 0.7.6 """ - z = universe.select_atoms(" atom %s %s C3\' " % (seg, i), " atom %s %s O3\' " % (seg, i), - " atom %s %s P " % (seg, i + 1), " atom %s %s O5\' " % (seg, i + 1)) + z = universe.select_atoms(" atom {0!s} {1!s} C3\' ".format(seg, i), " atom {0!s} {1!s} O3\' ".format(seg, i), + " atom {0!s} {1!s} P ".format(seg, i + 1), " atom {0!s} {1!s} O5\' ".format(seg, i + 1)) zeta = z.dihedral.value() if zeta < 0: zeta = zeta + 360 @@ -532,11 +532,11 @@ def tors_chi(universe, seg, i): .. versionadded:: 0.7.6 """ try: - c = universe.select_atoms(" atom %s %s O4\' " % (seg, i), " atom %s %s C1\' " % (seg, i), - " atom %s %s N1 " % (seg, i), " atom %s %s C2 " % (seg, i)) + c = universe.select_atoms(" atom {0!s} {1!s} O4\' ".format(seg, i), " atom {0!s} {1!s} C1\' ".format(seg, i), + " atom {0!s} {1!s} N1 ".format(seg, i), " atom {0!s} {1!s} C2 ".format(seg, i)) except: - c = universe.select_atoms(" atom %s %s O4\' " % (seg, i), " atom %s %s C1\' " % (seg, i), - " atom %s %s N9 " % (seg, i), " atom %s %s C4 " % (seg, i)) + c = universe.select_atoms(" atom {0!s} {1!s} O4\' ".format(seg, i), " atom {0!s} {1!s} C1\' ".format(seg, i), + " atom {0!s} {1!s} N9 ".format(seg, i), " atom {0!s} {1!s} C4 ".format(seg, i)) chi = c.dihedral.value() if chi < 0: chi = chi + 360 @@ -559,8 +559,8 @@ def hydroxyl(universe, seg, i): .. versionadded:: 0.7.6 """ - h = universe.select_atoms(" atom %s %s C1\' " % (seg, i), " atom %s %s C2\' " % (seg, i), - " atom %s %s O2\' " % (seg, i), " atom %s %s H2\'\' " % (seg, i)) + h = universe.select_atoms(" atom {0!s} {1!s} C1\' ".format(seg, i), " atom {0!s} {1!s} C2\' ".format(seg, i), + " atom {0!s} {1!s} O2\' ".format(seg, i), " atom {0!s} {1!s} H2\'\' ".format(seg, i)) try: hydr = h.dihedral.value() except ValueError: @@ -598,11 +598,11 @@ def pseudo_dihe_baseflip(universe, bp1, bp2, i, seg1="SYSTEM", seg2="SYSTEM", se .. versionadded:: 0.8.0 """ bf1 = universe.select_atoms( - " ( segid %s and resid %s and nucleicbase ) or ( segid %s and resid %s and nucleicbase ) " % ( + " ( segid {0!s} and resid {1!s} and nucleicbase ) or ( segid {2!s} and resid {3!s} and nucleicbase ) ".format( seg1, bp1, seg2, bp2)) - bf4 = universe.select_atoms(" ( segid %s and resid %s and nucleicbase ) " % (seg3, i)) - bf2 = universe.select_atoms(" ( segid %s and resid %s and nucleicsugar ) " % (seg2, bp2)) - bf3 = universe.select_atoms(" ( segid %s and resid %s and nucleicsugar ) " % (seg3, i)) + bf4 = universe.select_atoms(" ( segid {0!s} and resid {1!s} and nucleicbase ) ".format(seg3, i)) + bf2 = universe.select_atoms(" ( segid {0!s} and resid {1!s} and nucleicsugar ) ".format(seg2, bp2)) + bf3 = universe.select_atoms(" ( segid {0!s} and resid {1!s} and nucleicsugar ) ".format(seg3, i)) x = [bf1.center_of_mass(), bf2.center_of_mass(), bf3.center_of_mass(), bf4.center_of_mass()] pseudo = mdamath.dihedral(x[0] - x[1], x[1] - x[2], x[2] - x[3]) pseudo = np.rad2deg(pseudo) diff --git a/package/MDAnalysis/analysis/rms.py b/package/MDAnalysis/analysis/rms.py index 8571c22c737..5a008dad90d 100644 --- a/package/MDAnalysis/analysis/rms.py +++ b/package/MDAnalysis/analysis/rms.py @@ -320,20 +320,18 @@ def __init__(self, traj, reference=None, select='all', groupselections=None, fil if len(self.ref_atoms) != len(self.traj_atoms): logger.exception() raise SelectionError("Reference and trajectory atom selections do not contain " + - "the same number of atoms: N_ref=%d, N_traj=%d" % - (len(self.ref_atoms), len(self.traj_atoms))) - logger.info("RMS calculation for %d atoms." % len(self.ref_atoms)) + "the same number of atoms: N_ref={0:d}, N_traj={1:d}".format(len(self.ref_atoms), len(self.traj_atoms))) + logger.info("RMS calculation for {0:d} atoms.".format(len(self.ref_atoms))) mass_mismatches = (np.absolute(self.ref_atoms.masses - self.traj_atoms.masses) > self.tol_mass) if np.any(mass_mismatches): # diagnostic output: logger.error("Atoms: reference | trajectory") for ar, at in izip(self.ref_atoms, self.traj_atoms): if ar.name != at.name: - 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,)) - errmsg = "Inconsistent selections, masses differ by more than %f; mis-matching atoms are shown above." % \ - self.tol_mass + logger.error("{0:4!s} {1:3d} {2:3!s} {3:3!s} {4:6.3f} | {5:4!s} {6:3d} {7:3!s} {8:3!s} {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:f}; mis-matching atoms are shown above.".format( \ + self.tol_mass) logger.error(errmsg) raise SelectionError(errmsg) del mass_mismatches diff --git a/package/MDAnalysis/analysis/x3dna.py b/package/MDAnalysis/analysis/x3dna.py index 96554d0638b..c179ba0ebf3 100644 --- a/package/MDAnalysis/analysis/x3dna.py +++ b/package/MDAnalysis/analysis/x3dna.py @@ -352,10 +352,10 @@ def plot(self, **kwargs): ax.set_xlabel(r"Nucleic Acid Number") param = self.profiles.values()[0].dtype.names[k] if param in ["Shear", "Stretch", "Stagger", "Rise", "Shift", "Slide"]: - ax.set_ylabel("%s ($\AA$)" % (param)) + ax.set_ylabel("{0!s} ($\AA$)".format((param))) else: - ax.set_ylabel("%s (deg)" % (param)) - ax.figure.savefig("%s.png" % (param)) + ax.set_ylabel("{0!s} (deg)".format((param))) + ax.figure.savefig("{0!s}.png".format((param))) ax.figure.clf() def sorted_profiles_iter(self): @@ -438,7 +438,7 @@ def __init__(self, filename, **kwargs): self.x3dna_param = kwargs.pop('x3dna_param', True) self.exe['xdna_ensemble'] = which(x3dna_exe_name) if self.exe['xdna_ensemble'] is None: - errmsg = "X3DNA binary %(x3dna_exe_name)r not found." % vars() + errmsg = "X3DNA binary {x3dna_exe_name!r} not found.".format(**vars()) logger.fatal(errmsg) logger.fatal("%(x3dna_exe_name)r must be on the PATH or provided as keyword argument 'executable'.", vars()) @@ -533,7 +533,7 @@ def collect(self, **kwargs): length = len(filenames) if length == 0: logger.error("Glob pattern %r did not find any files.", self.filename) - raise ValueError("Glob pattern %r did not find any files." % (self.filename,)) + raise ValueError("Glob pattern {0!r} did not find any files.".format(self.filename)) logger.info("Found %d input files based on glob pattern %s", length, self.filename) # one recarray for each frame, indexed by frame number @@ -612,7 +612,7 @@ def collect(self, **kwargs): os.system("rm -f tmp*.out") if not os.path.exists(rundir): os.makedirs(rundir) - frame_x3dna_txt = os.path.join(rundir, "bp_step_%s_%04d.dat.gz" % (run, x3dna_profile_no)) + frame_x3dna_txt = os.path.join(rundir, "bp_step_{0!s}_{1:04d}.dat.gz".format(run, x3dna_profile_no)) np.savetxt(frame_x3dna_txt, frame_x3dna_output) logger.debug("Finished with frame %d, saved as %r", x3dna_profile_no, frame_x3dna_txt) # if we get here then we haven't found anything interesting @@ -703,7 +703,7 @@ def run(self, **kwargs): fd, pdbfile = tempfile.mkstemp(suffix=".pdb") os.close(fd) nucleic.write(pdbfile) - os.system("find_pair %s 355d.bps" % pdbfile) + os.system("find_pair {0!s} 355d.bps".format(pdbfile)) try: nucleic.write(pdbfile) ''' diff --git a/package/MDAnalysis/coordinates/LAMMPS.py b/package/MDAnalysis/coordinates/LAMMPS.py index 7f1b8299154..0fa8ee6cc91 100644 --- a/package/MDAnalysis/coordinates/LAMMPS.py +++ b/package/MDAnalysis/coordinates/LAMMPS.py @@ -109,9 +109,9 @@ def __init__(self, *args, **kwargs): for unit_type, unit in self.units.items(): try: if units.unit_types[unit] != unit_type: - raise TypeError("LAMMPS DCDWriter: wrong unit %r for unit type %r" % (unit, unit_type)) + raise TypeError("LAMMPS DCDWriter: wrong unit {0!r} for unit type {1!r}".format(unit, unit_type)) except KeyError: - raise ValueError("LAMMPS DCDWriter: unknown unit %r" % unit) + raise ValueError("LAMMPS DCDWriter: unknown unit {0!r}".format(unit)) super(DCDWriter, self).__init__(*args, **kwargs) @@ -135,9 +135,9 @@ def __init__(self, dcdfilename, **kwargs): for unit_type, unit in self.units.items(): try: if units.unit_types[unit] != unit_type: - raise TypeError("LAMMPS DCDReader: wrong unit %r for unit type %r" % (unit, unit_type)) + raise TypeError("LAMMPS DCDReader: wrong unit {0!r} for unit type {1!r}".format(unit, unit_type)) except KeyError: - raise ValueError("LAMMPS DCDReader: unknown unit %r" % unit) + raise ValueError("LAMMPS DCDReader: unknown unit {0!r}".format(unit)) super(DCDReader, self).__init__(dcdfilename, **kwargs) diff --git a/package/MDAnalysis/coordinates/PDB.py b/package/MDAnalysis/coordinates/PDB.py index e577b17e79d..ca70ffcb978 100644 --- a/package/MDAnalysis/coordinates/PDB.py +++ b/package/MDAnalysis/coordinates/PDB.py @@ -790,9 +790,9 @@ def close(self): def _write_pdb_title(self): if self.multiframe: - self.TITLE("MDANALYSIS FRAMES FROM %d, SKIP %d: %s" % (self.start, self.step, self.remarks)) + self.TITLE("MDANALYSIS FRAMES FROM {0:d}, SKIP {1:d}: {2!s}".format(self.start, self.step, self.remarks)) else: - self.TITLE("MDANALYSIS FRAME %d: %s" % (self.start, self.remarks)) + self.TITLE("MDANALYSIS FRAME {0:d}: {1!s}".format(self.start, self.remarks)) def _write_pdb_header(self): if not self.obj or not hasattr(self.obj, 'universe'): @@ -844,8 +844,7 @@ def _check_pdb_coordinates(self): if err.errno == errno.ENOENT: pass raise ValueError( - "PDB files must have coordinate values between %.3f and %.3f Angstroem: file writing was aborted." % - (self.pdb_coor_limits["min"], self.pdb_coor_limits["max"])) + "PDB files must have coordinate values between {0:.3f} and {1:.3f} Angstroem: file writing was aborted.".format(self.pdb_coor_limits["min"], self.pdb_coor_limits["max"])) def _write_pdb_bonds(self): """Writes out all the bond records; works only for Universe objects. @@ -1091,7 +1090,7 @@ def _write_timestep(self, ts, multiframe=False): if len(atoms) != len(coor): raise ValueError( - "Length of the atoms array is %d, this is different form the Timestep coordinate array %d" % ( + "Length of the atoms array is {0:d}, this is different form the Timestep coordinate array {1:d}".format( len(atoms), len(ts._pos))) if multiframe: @@ -1263,7 +1262,7 @@ def CONECT(self, conect): .. _CONECT: http://www.wwpdb.org/documentation/format32/sect10.html#CONECT """ - conect = ["%5d" % (entry + 1) for entry in conect] + conect = ["{0:5d}".format((entry + 1)) for entry in conect] conect = "".join(conect) self.pdbfile.write(self.fmt['CONECT'] % conect) diff --git a/package/MDAnalysis/coordinates/PDBQT.py b/package/MDAnalysis/coordinates/PDBQT.py index f0d816280e1..7c9205528e7 100644 --- a/package/MDAnalysis/coordinates/PDBQT.py +++ b/package/MDAnalysis/coordinates/PDBQT.py @@ -304,8 +304,7 @@ def write(self, selection, frame=None): if err.errno == errno.ENOENT: pass raise ValueError( - "PDB files must have coordinate values between %.3f and %.3f Angstroem: No file was written." % - (self.pdb_coor_limits["min"], self.pdb_coor_limits["max"])) + "PDB files must have coordinate values between {0:.3f} and {1:.3f} Angstroem: No file was written.".format(self.pdb_coor_limits["min"], self.pdb_coor_limits["max"])) for i, atom in enumerate(atoms): self.ATOM(serial=i + 1, name=atom.name.strip(), resName=atom.resname.strip(), resSeq=atom.resid, diff --git a/package/MDAnalysis/coordinates/TRJ.py b/package/MDAnalysis/coordinates/TRJ.py index 8f3c0141e0f..6f272b7648d 100644 --- a/package/MDAnalysis/coordinates/TRJ.py +++ b/package/MDAnalysis/coordinates/TRJ.py @@ -211,7 +211,7 @@ def __init__(self, filename, n_atoms=None, **kwargs): # We determine right away what parser we need for the last # line because it will be the same for all frames. last_per_line = 3 * self.n_atoms % len(self.default_line_parser) - self.last_line_parser = util.FORTRANReader("%dF8.3" % last_per_line) + self.last_line_parser = util.FORTRANReader("{0:d}F8.3".format(last_per_line)) # FORMAT(10F8.3) BOX(1), BOX(2), BOX(3) # is this always on a separate line?? @@ -435,7 +435,7 @@ def __init__(self, filename, n_atoms=None, **kwargs): logger.fatal(errmsg) raise TypeError(errmsg) if not self.trjfile.ConventionVersion == self.version: - wmsg = "NCDF trajectory format is %s but the reader implements format %s" % ( + wmsg = "NCDF trajectory format is {0!s} but the reader implements format {1!s}".format( self.trjfile.ConventionVersion, self.version) warnings.warn(wmsg) logger.warn(wmsg) diff --git a/package/MDAnalysis/coordinates/XYZ.py b/package/MDAnalysis/coordinates/XYZ.py index 49ac1d4ce12..6b9bcfcbf88 100644 --- a/package/MDAnalysis/coordinates/XYZ.py +++ b/package/MDAnalysis/coordinates/XYZ.py @@ -246,7 +246,7 @@ def write_next_timestep(self, ts=None): self._xyz.write("{0:d}\n".format(ts.n_atoms)) self._xyz.write("frame {0}\n".format(ts.frame)) for atom, (x, y, z) in itertools.izip(self.atomnames, coordinates): - self._xyz.write("%8s %10.5f %10.5f %10.5f\n" % (atom, x, y, z)) + self._xyz.write("{0:8!s} {1:10.5f} {2:10.5f} {3:10.5f}\n".format(atom, x, y, z)) class XYZReader(base.Reader): diff --git a/package/MDAnalysis/coordinates/base.py b/package/MDAnalysis/coordinates/base.py index 1f1c901bb0c..57c036d137e 100644 --- a/package/MDAnalysis/coordinates/base.py +++ b/package/MDAnalysis/coordinates/base.py @@ -1128,8 +1128,7 @@ def _check_slice_indices(self, start, stop, step): return start, stop, step def __repr__(self): - return "< %s %r with %d frames of %d atoms>" % \ - (self.__class__.__name__, self.filename, self.n_frames, self.n_atoms) + return "< {0!s} {1!r} with {2:d} frames of {3:d} atoms>".format(self.__class__.__name__, self.filename, self.n_frames, self.n_atoms) class Reader(ProtoReader): @@ -1305,7 +1304,7 @@ def _get_local_frame(self, k): # trajectory index i i = bisect.bisect_right(self.__start_frames, k) - 1 if i < 0: - raise IndexError("Cannot find trajectory for virtual frame %d" % k) + raise IndexError("Cannot find trajectory for virtual frame {0:d}".format(k)) # local frame index f in trajectory i (frame indices are 0-based) f = k - self.__start_frames[i] return i, f @@ -1393,7 +1392,7 @@ def __activate_reader(self, i): """Make reader *i* the active reader.""" # private method, not to be used by user to avoid a total mess if i < 0 or i >= len(self.readers): - raise IndexError("Reader index must be 0 <= i < %d" % len(self.readers)) + raise IndexError("Reader index must be 0 <= i < {0:d}".format(len(self.readers))) self.__active_reader_index = i @property @@ -1465,8 +1464,7 @@ def get_flname(self, filename): # retrieve the actual filename of the list elem return filename[0] if isinstance(filename, tuple) else filename def __repr__(self): - return "< %s %r with %d frames of %d atoms>" % \ - (self.__class__.__name__, + return "< {0!s} {1!r} with {2:d} frames of {3:d} atoms>".format(self.__class__.__name__, [os.path.basename(self.get_flname(fn)) for fn in self.filenames], self.n_frames, self.n_atoms) @@ -1521,10 +1519,10 @@ def __del__(self): def __repr__(self): try: - return "< %s %r for %d atoms >" % (self.__class__.__name__, self.filename, self.n_atoms) + return "< {0!s} {1!r} for {2:d} atoms >".format(self.__class__.__name__, self.filename, self.n_atoms) except (TypeError, AttributeError): # no trajectory loaded yet or a Writer that does not need e.g. self.n_atoms - return "< %s %r >" % (self.__class__.__name__, self.filename) + return "< {0!s} {1!r} >".format(self.__class__.__name__, self.filename) def has_valid_coordinates(self, criteria, x): """Returns ``True`` if all values are within limit values of their formats. diff --git a/package/MDAnalysis/coordinates/core.py b/package/MDAnalysis/coordinates/core.py index 769e0a112e8..f53391ae9c7 100644 --- a/package/MDAnalysis/coordinates/core.py +++ b/package/MDAnalysis/coordinates/core.py @@ -135,19 +135,19 @@ def get_writer_for(filename=None, format='DCD', multiframe=None): try: return _frame_writers[format] except KeyError: - raise TypeError("No trajectory or frame writer for format %r" % format) + raise TypeError("No trajectory or frame writer for format {0!r}".format(format)) elif multiframe is True: try: return _trajectory_writers[format] except KeyError: - raise TypeError("No trajectory writer for format %r" % format) + raise TypeError("No trajectory writer for format {0!r}".format(format)) elif multiframe is False: try: return _frame_writers[format] except KeyError: - raise TypeError("No single frame writer for format %r" % format) + raise TypeError("No single frame writer for format {0!r}".format(format)) else: - raise ValueError("Unknown value %r for multiframe, only True, False, None allowed" % multiframe) + raise ValueError("Unknown value {0!r} for multiframe, only True, False, None allowed".format(multiframe)) def writer(filename, n_atoms=None, **kwargs): diff --git a/package/MDAnalysis/coordinates/pdb/extensions.py b/package/MDAnalysis/coordinates/pdb/extensions.py index 718c6ec4e31..1ebb5184e5f 100644 --- a/package/MDAnalysis/coordinates/pdb/extensions.py +++ b/package/MDAnalysis/coordinates/pdb/extensions.py @@ -109,9 +109,8 @@ def init_residue(self, resname, field, resseq, icode): fudged_resseq = True if fudged_resseq and self.verbose: - logger.debug("Residues are wrapping (Residue ('%s', %i, '%s') at line %i)." - % (field, resseq, icode, self.line_counter) + - ".... assigning new resid %d.\n" % self.max_resseq) + logger.debug("Residues are wrapping (Residue ('{0!s}', {1:d}, '{2!s}') at line {3:d}).".format(field, resseq, icode, self.line_counter) + + ".... assigning new resid {0:d}.\n".format(self.max_resseq)) residue = Bio.PDB.Residue.Residue(res_id, resname, self.segid) self.chain.add(residue) self.residue = residue diff --git a/package/MDAnalysis/coordinates/xdrfile/core.py b/package/MDAnalysis/coordinates/xdrfile/core.py index 123f9de94cc..24a03f06ce7 100644 --- a/package/MDAnalysis/coordinates/xdrfile/core.py +++ b/package/MDAnalysis/coordinates/xdrfile/core.py @@ -217,7 +217,7 @@ def write_next_timestep(self, ts=None): status = self._write_next_timestep(ts) if status != libxdrfile2.exdrOK: - raise IOError(errno.EIO, "Error writing %s file (status %d)" % (self.format, status), self.filename) + raise IOError(errno.EIO, "Error writing {0!s} file (status {1:d})".format(self.format, status), self.filename) self.frames_written += 1 def _write_next_timestep(self, ts): diff --git a/package/MDAnalysis/coordinates/xdrfile/libxdrfile2.py b/package/MDAnalysis/coordinates/xdrfile/libxdrfile2.py index a09bb118730..43ec614f778 100644 --- a/package/MDAnalysis/coordinates/xdrfile/libxdrfile2.py +++ b/package/MDAnalysis/coordinates/xdrfile/libxdrfile2.py @@ -435,7 +435,7 @@ def _swig_setattr_nondynamic(self, class_type, name, value, static=1): if (not static): self.__dict__[name] = value else: - raise AttributeError("You cannot add attributes to %s" % self) + raise AttributeError("You cannot add attributes to {0!s}".format(self)) def _swig_setattr(self, class_type, name, value): @@ -456,7 +456,7 @@ def _swig_repr(self): strthis = "proxy of " + self.this.__repr__() except: strthis = "" - return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) + return "<{0!s}.{1!s}; {2!s} >".format(self.__class__.__module__, self.__class__.__name__, strthis) try: diff --git a/package/MDAnalysis/coordinates/xdrfile/src/libxdrfile2.py b/package/MDAnalysis/coordinates/xdrfile/src/libxdrfile2.py index ccfeed633bd..9c1daab757a 100644 --- a/package/MDAnalysis/coordinates/xdrfile/src/libxdrfile2.py +++ b/package/MDAnalysis/coordinates/xdrfile/src/libxdrfile2.py @@ -396,7 +396,7 @@ def _swig_setattr_nondynamic(self, class_type, name, value, static=1): if (not static): self.__dict__[name] = value else: - raise AttributeError("You cannot add attributes to %s" % self) + raise AttributeError("You cannot add attributes to {0!s}".format(self)) def _swig_setattr(self, class_type, name, value): @@ -417,7 +417,7 @@ def _swig_repr(self): strthis = "proxy of " + self.this.__repr__() except: strthis = "" - return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) + return "<{0!s}.{1!s}; {2!s} >".format(self.__class__.__module__, self.__class__.__name__, strthis) try: diff --git a/package/MDAnalysis/core/AtomGroup.py b/package/MDAnalysis/core/AtomGroup.py index c1da11f8324..06aff2c0340 100644 --- a/package/MDAnalysis/core/AtomGroup.py +++ b/package/MDAnalysis/core/AtomGroup.py @@ -3104,7 +3104,7 @@ def phi_selection(self): method returns ``None``. """ sel = self.universe.select_atoms( - 'segid %s and resid %d and name C' % (self.segment.id, self.id - 1)) + \ + 'segid {0!s} and resid {1:d} and name C'.format(self.segment.id, self.id - 1)) + \ self['N'] + self['CA'] + self['C'] if len(sel) == 4: # select_atoms doesnt raise errors if nothing found, so check size return sel @@ -3120,7 +3120,7 @@ def psi_selection(self): """ sel = self['N'] + self['CA'] + self['C'] + \ self.universe.select_atoms( - 'segid %s and resid %d and name N' % (self.segment.id, self.id + 1)) + 'segid {0!s} and resid {1:d} and name N'.format(self.segment.id, self.id + 1)) if len(sel) == 4: return sel else: @@ -3142,8 +3142,8 @@ def omega_selection(self): segid = self.segment.id sel = self['CA'] + self['C'] + \ self.universe.select_atoms( - 'segid %s and resid %d and name N' % (segid, nextres), - 'segid %s and resid %d and name CA' % (segid, nextres)) + 'segid {0!s} and resid {1:d} and name N'.format(segid, nextres), + 'segid {0!s} and resid {1:d} and name CA'.format(segid, nextres)) if len(sel) == 4: return sel else: @@ -4640,7 +4640,7 @@ def as_Universe(*args, **kwargs): :Returns: an instance of :class:`~MDAnalaysis.AtomGroup.Universe` """ if len(args) == 0: - raise TypeError("as_Universe() takes at least one argument (%d given)" % len(args)) + raise TypeError("as_Universe() takes at least one argument ({0:d} given)".format(len(args))) elif len(args) == 1 and isinstance(args[0], Universe): return args[0] return Universe(*args, **kwargs) diff --git a/package/MDAnalysis/core/Selection.py b/package/MDAnalysis/core/Selection.py index 1ff68d109f7..44adbfabab1 100644 --- a/package/MDAnalysis/core/Selection.py +++ b/package/MDAnalysis/core/Selection.py @@ -300,11 +300,11 @@ def _apply(self, group): cyl_z_hheight = (self.zmax-self.zmin)/2 if 2*self.exRadius > box[0]: - raise NotImplementedError("The diameter of the cylinder selection (%.3f) is larger than the unit cell's x dimension (%.3f). Can only do selections where it is smaller or equal." % (2*self.exRadius, box[0])) + raise NotImplementedError("The diameter of the cylinder selection ({0:.3f}) is larger than the unit cell's x dimension ({1:.3f}). Can only do selections where it is smaller or equal.".format(2*self.exRadius, box[0])) if 2*self.exRadius > box[1]: - raise NotImplementedError("The diameter of the cylinder selection (%.3f) is larger than the unit cell's y dimension (%.3f). Can only do selections where it is smaller or equal." % (2*self.exRadius, box[1])) + raise NotImplementedError("The diameter of the cylinder selection ({0:.3f}) is larger than the unit cell's y dimension ({1:.3f}). Can only do selections where it is smaller or equal.".format(2*self.exRadius, box[1])) if 2*cyl_z_hheight > box[2]: - raise NotImplementedError("The total length of the cylinder selection in z (%.3f) is larger than the unit cell's z dimension (%.3f). Can only do selections where it is smaller or equal." % (2*cyl_z_hheight, box[2])) + raise NotImplementedError("The total length of the cylinder selection in z ({0:.3f}) is larger than the unit cell's z dimension ({1:.3f}). Can only do selections where it is smaller or equal.".format(2*cyl_z_hheight, box[2])) #how off-center in z is our CoG relative to the cylinder's center cyl_center = sel_CoG + [0,0,(self.zmax+self.zmin)/2] coords += box/2 - cyl_center diff --git a/package/MDAnalysis/core/Timeseries.py b/package/MDAnalysis/core/Timeseries.py index 8997738a5b3..e5e11b2f9bd 100644 --- a/package/MDAnalysis/core/Timeseries.py +++ b/package/MDAnalysis/core/Timeseries.py @@ -92,7 +92,7 @@ def __repr__(self): suffix = 's' else: suffix = '' - return '<' + self.__class__.__name__ + ' with %d timeseries object%s>' % (len(self), suffix) + return '<' + self.__class__.__name__ + ' with {0:d} timeseries object{1!s}>'.format(len(self), suffix) def addTimeseries(self, ts): '''add a Timeseries object to the collection''' @@ -175,7 +175,7 @@ def __init__(self, code, atoms, dsize): elif isinstance(atoms, AtomGroup.Atom): self.atoms = [atoms] else: - raise TypeError("Invalid atoms passed to %s timeseries" % self.__class__.__name__) + raise TypeError("Invalid atoms passed to {0!s} timeseries".format(self.__class__.__name__)) self.code = code self.n_atoms = len(self.atoms) self.dsize = dsize @@ -194,8 +194,8 @@ def __len__(self): def __repr__(self): if hasattr(self, "__data__"): - return '<' + self.__class__.__name__ + ' timeseries object is populated with data>\n%s' % \ - (repr(self.__data__)) + return '<' + self.__class__.__name__ + ' timeseries object is populated with data>\n{0!s}'.format( \ + (repr(self.__data__))) else: return '<' + self.__class__.__name__ + ' timeseries object is not populated with data>' @@ -247,7 +247,7 @@ def __init__(self, code, atoms): elif isinstance(atoms, AtomGroup.Atom): n_atoms = 1 else: - raise TypeError("Invalid atoms passed to %s timeseries" % self.__class__.__name__) + raise TypeError("Invalid atoms passed to {0!s} timeseries".format(self.__class__.__name__)) Timeseries.__init__(self, code * n_atoms, atoms, size * n_atoms) def getAtomCounts(self): diff --git a/package/MDAnalysis/core/__init__.py b/package/MDAnalysis/core/__init__.py index 53bceacea92..76b39d33464 100644 --- a/package/MDAnalysis/core/__init__.py +++ b/package/MDAnalysis/core/__init__.py @@ -222,7 +222,7 @@ def prop(self): return {'fget': self.get, 'fset': self.set, 'doc': self.__doc__} def __repr__(self): - return """Flag('%(name)s',%(value)r)""" % self.__dict__ + return """Flag('{name!s}',{value!r})""".format(**self.__dict__) class _Flag(Flag): diff --git a/package/MDAnalysis/lib/transformations.py b/package/MDAnalysis/lib/transformations.py index 60f18c1c939..48f5434effb 100644 --- a/package/MDAnalysis/lib/transformations.py +++ b/package/MDAnalysis/lib/transformations.py @@ -702,7 +702,7 @@ def shear_from_matrix(matrix): l, V = np.linalg.eig(M33) i = np.where(abs(np.real(l) - 1.0) < 1e-4)[0] if len(i) < 2: - raise ValueError("no two linear independent eigenvectors found %s" % l) + raise ValueError("no two linear independent eigenvectors found {0!s}".format(l)) V = np.real(V[:, i]).squeeze().T lenorm = -1.0 for i0, i1 in ((0, 1), (0, 2), (1, 2)): diff --git a/package/MDAnalysis/lib/util.py b/package/MDAnalysis/lib/util.py index 1f2a2f05ab5..9421e175686 100644 --- a/package/MDAnalysis/lib/util.py +++ b/package/MDAnalysis/lib/util.py @@ -309,7 +309,7 @@ def anyopen(datasource, mode='r', reset=True): if not stream is None: break if stream is None: - raise IOError(errno.EIO, "Cannot open file or stream in mode=%(mode)r." % vars(), repr(filename)) + raise IOError(errno.EIO, "Cannot open file or stream in mode={mode!r}.".format(**vars()), repr(filename)) elif mode.startswith('w') or mode.startswith('a'): # append 'a' not tested... if isstream(datasource): stream = datasource @@ -328,9 +328,9 @@ def anyopen(datasource, mode='r', reset=True): openfunc = handlers[ext] stream = openfunc(datasource, mode=mode) if stream is None: - raise IOError(errno.EIO, "Cannot open file or stream in mode=%(mode)r." % vars(), repr(filename)) + raise IOError(errno.EIO, "Cannot open file or stream in mode={mode!r}.".format(**vars()), repr(filename)) else: - raise NotImplementedError("Sorry, mode=%(mode)r is not implemented for %(datasource)r" % vars()) + raise NotImplementedError("Sorry, mode={mode!r} is not implemented for {datasource!r}".format(**vars())) try: stream.name = filename except (AttributeError, TypeError): @@ -876,14 +876,14 @@ def read(self, line): try: return self.convertor(line[self.start:self.stop]) except ValueError: - raise ValueError("%r: Failed to read&convert %r" % (self, line[self.start:self.stop])) + raise ValueError("{0!r}: Failed to read&convert {1!r}".format(self, line[self.start:self.stop])) def __len__(self): """Length of the field in columns (stop - start)""" return self.stop - self.start def __repr__(self): - return "FixedcolumnEntry(%d,%d,%r)" % (self.start, self.stop, self.typespecifier) + return "FixedcolumnEntry({0:d},{1:d},{2!r})".format(self.start, self.stop, self.typespecifier) class FORTRANReader(object): @@ -974,7 +974,7 @@ def parse_FORTRAN_format(self, edit_descriptor): if m is None: raise ValueError # really no idea what the descriptor is supposed to mean except: - raise ValueError("unrecognized FORTRAN format %r" % edit_descriptor) + raise ValueError("unrecognized FORTRAN format {0!r}".format(edit_descriptor)) d = m.groupdict() if d['repeat'] == '': d['repeat'] = 1 @@ -1106,7 +1106,7 @@ def parse_residue(residue): # XXX: use _translate_residue() .... m = RESIDUE.match(residue) if not m: - raise ValueError("Selection %(residue)r is not valid (only 1/3/4 letter resnames, resid required)." % vars()) + raise ValueError("Selection {residue!r} is not valid (only 1/3/4 letter resnames, resid required).".format(**vars())) resid = int(m.group('resid')) residue = m.group('aa') if len(residue) == 1: diff --git a/package/MDAnalysis/selections/__init__.py b/package/MDAnalysis/selections/__init__.py index 13c696983e7..b5fa501da43 100644 --- a/package/MDAnalysis/selections/__init__.py +++ b/package/MDAnalysis/selections/__init__.py @@ -68,5 +68,4 @@ def get_writer(filename, defaultformat): try: return _selection_writers[format] except KeyError: - raise NotImplementedError("Writing as %r is not implemented; only %r will work." - % (format, _selection_writers.keys())) + raise NotImplementedError("Writing as {0!r} is not implemented; only {1!r} will work.".format(format, _selection_writers.keys())) diff --git a/package/MDAnalysis/selections/base.py b/package/MDAnalysis/selections/base.py index 60e2886364e..69c221789ce 100644 --- a/package/MDAnalysis/selections/base.py +++ b/package/MDAnalysis/selections/base.py @@ -99,7 +99,7 @@ def __init__(self, filename, mode="wa", numterms=None, preamble=None, **kwargs): """ self.filename = util.filename(filename, ext=self.ext) if not mode in ('a', 'w', 'wa'): - raise ValueError("mode must be one of 'w', 'a', 'wa', not %r" % mode) + raise ValueError("mode must be one of 'w', 'a', 'wa', not {0!r}".format(mode)) self.mode = mode self._current_mode = mode[0] if numterms is None or numterms < 0: @@ -165,7 +165,7 @@ def write(self, selection, number=None, name=None, frame=None, mode=None): if number is None: self.number += 1 number = self.number - name = "mdanalysis%(number)03d" % vars() + name = "mdanalysis{number:03d}".format(**vars()) # build whole selection in one go (cleaner way to deal with # to deal with line breaks after self.numterms entries) # selection_list must contain entries to be joined with spaces or linebreaks diff --git a/package/MDAnalysis/selections/charmm.py b/package/MDAnalysis/selections/charmm.py index 9555cd526c4..b55caaa88c9 100644 --- a/package/MDAnalysis/selections/charmm.py +++ b/package/MDAnalysis/selections/charmm.py @@ -46,13 +46,13 @@ class SelectionWriter(base.SelectionWriter): def _translate(self, atoms, **kwargs): # CHARMM index is 1-based def _index(atom): - return "BYNUM %d" % (atom.index + 1) + return "BYNUM {0:d}".format((atom.index + 1)) return base.join(atoms, ' .or.', _index) def _write_head(self, out, **kwargs): out.write(self.comment("MDAnalysis CHARMM selection")) - out.write("DEFINE %(name)s SELECT " % kwargs + self.continuation + '\n') + out.write("DEFINE {name!s} SELECT ".format(**kwargs) + self.continuation + '\n') def _write_tail(self, out, **kwargs): out.write("END") diff --git a/package/MDAnalysis/selections/gromacs.py b/package/MDAnalysis/selections/gromacs.py index c67eb5acd69..89baa9acdd9 100644 --- a/package/MDAnalysis/selections/gromacs.py +++ b/package/MDAnalysis/selections/gromacs.py @@ -46,6 +46,6 @@ def _translate(self, atoms, **kwargs): return [str(atom.index + 1) for atom in atoms] def _write_head(self, out, **kwargs): - out.write("[ %(name)s ]\n" % kwargs) + out.write("[ {name!s} ]\n".format(**kwargs)) diff --git a/package/MDAnalysis/selections/jmol.py b/package/MDAnalysis/selections/jmol.py index ffafe99940b..fa566418e55 100644 --- a/package/MDAnalysis/selections/jmol.py +++ b/package/MDAnalysis/selections/jmol.py @@ -50,7 +50,7 @@ def _index(atom): return base.join(atoms, ' ', _index) def _write_head(self, out, **kwargs): - out.write("@~%(name)s ({" % kwargs) + out.write("@~{name!s} ({{".format(**kwargs)) def _write_tail(self, out, **kwargs): out.write("});") diff --git a/package/MDAnalysis/selections/pymol.py b/package/MDAnalysis/selections/pymol.py index d4a5418339d..65e8beebdff 100644 --- a/package/MDAnalysis/selections/pymol.py +++ b/package/MDAnalysis/selections/pymol.py @@ -47,10 +47,10 @@ class SelectionWriter(base.SelectionWriter): def _translate(self, atoms, **kwargs): # PyMol index is 1-based def _index(atom): - return "index %d" % (atom.index + 1) + return "index {0:d}".format((atom.index + 1)) return base.join(atoms, ' |', _index) def _write_head(self, out, **kwargs): out.write(self.comment("MDAnalysis PyMol selection")) - out.write("select %(name)s, " % kwargs + self.continuation + '\n') + out.write("select {name!s}, ".format(**kwargs) + self.continuation + '\n') diff --git a/package/MDAnalysis/selections/vmd.py b/package/MDAnalysis/selections/vmd.py index fb9c067a670..459058af9fe 100644 --- a/package/MDAnalysis/selections/vmd.py +++ b/package/MDAnalysis/selections/vmd.py @@ -43,7 +43,7 @@ class SelectionWriter(base.SelectionWriter): def _write_head(self, out, **kwargs): out.write(self.comment("MDAnalysis VMD selection")) - out.write("atomselect macro %(name)s {index " % kwargs) + out.write("atomselect macro {name!s} {{index ".format(**kwargs)) def _translate(self, atoms, **kwargs): # VMD index is 0-based (as is MDAnalysis) diff --git a/package/examples/amber2dcd.py b/package/examples/amber2dcd.py index 3a91f2270d4..85c0934612e 100755 --- a/package/examples/amber2dcd.py +++ b/package/examples/amber2dcd.py @@ -33,11 +33,11 @@ # loop through the trajectory and write a frame for every step for ts in u.trajectory: w.write(ts) - print "Converted frame %d" % ts.frame + print "Converted frame {0:d}".format(ts.frame) w.close_trajectory() -print "Converted %r --> %r" % (intrj, outtrj) +print "Converted {0!r} --> {1!r}".format(intrj, outtrj) # make a pdb file as a simple 'topology' u.trajectory.rewind() u.atoms.write(outpdb) -print "Created %r to be used with the trajectory" % outpdb +print "Created {0!r} to be used with the trajectory".format(outpdb) diff --git a/package/examples/backbone_dihedral.py b/package/examples/backbone_dihedral.py index 7b0769c7a2c..b2b8f377aec 100755 --- a/package/examples/backbone_dihedral.py +++ b/package/examples/backbone_dihedral.py @@ -32,7 +32,7 @@ collection.clear() for res in range(2, numresidues - 1): - print "Processing residue %d" % res + print "Processing residue {0:d}".format(res) # selection of the atoms involved for the phi for resid '%d' %res ## select_atoms("atom 4AKE %d C"%(res-1), "atom 4AKE %d N"%res, "atom %d 4AKE CA"%res, "atom 4AKE %d C" % res) phi_sel = universe.residues[res].phi_selection() diff --git a/package/examples/blocks.py b/package/examples/blocks.py index 0d0c534b5bf..f7b53dd1233 100755 --- a/package/examples/blocks.py +++ b/package/examples/blocks.py @@ -68,4 +68,4 @@ def rgyr(universe): savefig("./figures/blocks.pdf") savefig("./figures/blocks.png") - print "Wrote ./figures/blocks.{pdf,png}" % vars() + print "Wrote ./figures/blocks.{{pdf,png}}".format(*vars()) diff --git a/package/examples/dcd2xtc.py b/package/examples/dcd2xtc.py index 016be7c9312..fb7e802e64d 100755 --- a/package/examples/dcd2xtc.py +++ b/package/examples/dcd2xtc.py @@ -26,6 +26,6 @@ # loop through the trajectory and write a frame for every step for ts in u.trajectory: w.write(ts) - print "Converted frame %d" % ts.frame + print "Converted frame {0:d}".format(ts.frame) w.close_trajectory() -print "Converted %r --> %r" % (DCD, xtcname) +print "Converted {0!r} --> {1!r}".format(DCD, xtcname) diff --git a/package/examples/lipid_order_parameters.py b/package/examples/lipid_order_parameters.py index 3132004b26b..1337da1446e 100755 --- a/package/examples/lipid_order_parameters.py +++ b/package/examples/lipid_order_parameters.py @@ -9,8 +9,8 @@ order_param = np.zeros(len(tail_carbons)) for i, carbon in enumerate(tail_carbons): - selection = "resname DMPC and ( name C2%d or name H%dR or name H%dS or name C3%d or name H%dX or name H%dY )" % \ - ((carbon,) * 6) + selection = "resname DMPC and ( name C2{0:d} or name H{1:d}R or name H{2:d}S or name C3{3:d} or name H{4:d}X or name H{5:d}Y )".format(* \ + ((carbon,) * 6)) group = universe.select_atoms(selection) data = universe.dcd.timeseries(group, format="afc", skip=skip) diff --git a/package/examples/membrane-composition.py b/package/examples/membrane-composition.py index de116eec865..71f91ca9fc3 100755 --- a/package/examples/membrane-composition.py +++ b/package/examples/membrane-composition.py @@ -86,21 +86,21 @@ max_imbalance=options.max_imbalance) except: raise RuntimeError("Failed cutoff optimization, try without --optimize") - print "# Optimized cutoff=%(cutoff).1f A, finding %(N)d disconnected groups" % vars() + print "# Optimized cutoff={cutoff:.1f} A, finding {N:d} disconnected groups".format(**vars()) else: cutoff = options.cutoff - print "# Using fixed cutoff=%(cutoff).1f A" % vars() + print "# Using fixed cutoff={cutoff:.1f} A".format(**vars()) LF = LeafletFinder(u, options.selection, cutoff=cutoff, pbc=options.pbc) - print "# group sizes = %r " % LF.sizes() + print "# group sizes = {0!r} ".format(LF.sizes()) # two leaflets def print_line(symbol="-"): print "#" + (12 + 5) * symbol print_line("=") - print "#%2s %5s %6s" % ("ll", "resn", "count") + print "#{0:2!s} {1:5!s} {2:6!s}".format("ll", "resn", "count") print_line("=") for groupindex in xrange(len(LF.components)): @@ -109,9 +109,9 @@ def print_line(symbol="-"): keys = np.unique(resnames) for k in keys: count = resnames.count(k) - print " %2d %5s %6d" % (groupindex, k, count) + print " {0:2d} {1:5!s} {2:6d}".format(groupindex, k, count) total = LF.sizes()[groupindex] if total > 1: print_line() - print "#%2d %5s %6d" % (groupindex, '', total) + print "#{0:2d} {1:5!s} {2:6d}".format(groupindex, '', total) print diff --git a/package/examples/membrane-leaflets.py b/package/examples/membrane-leaflets.py index 0c0ba9882f2..17ff3d174b8 100755 --- a/package/examples/membrane-leaflets.py +++ b/package/examples/membrane-leaflets.py @@ -38,9 +38,9 @@ except ValueError: print "usage: leaflet.py PDB SELECTION" sys.exit(1) - print "PDB=%(PDB)r selection=%(selection)r" % vars() + print "PDB={PDB!r} selection={selection!r}".format(**vars()) L = LeafletFinder(PDB, selection) - print "Number of lipids in leaflets: %r" % L.sizes() + print "Number of lipids in leaflets: {0!r}".format(L.sizes()) macrovmd = PDB + ".vmd" L.write_vmd(macrovmd) - print "Load macros for vmd from file %r" % macrovmd + print "Load macros for vmd from file {0!r}".format(macrovmd) diff --git a/package/examples/membrane-parameters.py b/package/examples/membrane-parameters.py index 38b075617ff..11e39be5837 100755 --- a/package/examples/membrane-parameters.py +++ b/package/examples/membrane-parameters.py @@ -122,16 +122,16 @@ def get_membrane_parameters(universe, leafletfinder): max_imbalance=options.max_imbalance) except: raise RuntimeError("Failed cutoff optimization, try without --optimize") - print "# Optimized cutoff=%(cutoff).1f A, finding %(N)d disconnected groups" % vars() + print "# Optimized cutoff={cutoff:.1f} A, finding {N:d} disconnected groups".format(**vars()) else: cutoff = options.cutoff - print "# Using fixed cutoff=%(cutoff).1f A" % vars() + print "# Using fixed cutoff={cutoff:.1f} A".format(**vars()) LF = LeafletFinder(u, options.selection, cutoff=cutoff, pbc=options.pbc) p = get_membrane_parameters(u, LF) # show results print "#" + 60 * "=" - print "thickness tmem = %(thickness).2f A" % p - print "center zmem = %(zmem).2f A" % p + print "thickness tmem = {thickness:.2f} A".format(**p) + print "center zmem = {zmem:.2f} A".format(**p) print "#" + 60 * "=" diff --git a/package/examples/multimers-analysis.py b/package/examples/multimers-analysis.py index fcdf6a807ce..a64561db20d 100755 --- a/package/examples/multimers-analysis.py +++ b/package/examples/multimers-analysis.py @@ -69,7 +69,7 @@ def define_peptides(number_of_peptides, lenght_of_peptide): lookup = {} for i in range(number_of_peptides): - selection[i] = "resid %d-%d" % (lenght_of_peptide * i + 1, lenght_of_peptide * (i + 1)) + selection[i] = "resid {0:d}-{1:d}".format(lenght_of_peptide * i + 1, lenght_of_peptide * (i + 1)) index = lenght_of_peptide * i + 1 while (index <= lenght_of_peptide * (i + 1)): lookup[index] = i @@ -88,7 +88,7 @@ def analyze(partners={}, clusters={}, multimers=[{}, {}, {}, {}], skip=1000): for ts in universe.trajectory: if not ts.frame % skip == 0 and ts.frame != 1: continue - print "Stepping... Frame %d, time %d ns" % (ts.frame, ts.time / 1000) + print "Stepping... Frame {0:d}, time {1:d} ns".format(ts.frame, ts.time / 1000) p = find_partners(peptide_selection, peptide_dictionary) partners[ts.frame] = p @@ -124,7 +124,7 @@ def find_partners(peptide_list, lookup): """ ret = {} for id, selection in peptide_list.items(): - atom_list = universe.select_atoms("around %d (%s) and not resname W" % (cutoff, selection)) + atom_list = universe.select_atoms("around {0:d} ({1!s}) and not resname W".format(cutoff, selection)) ret[id] = set() for atom in atom_list: if atom.resname == "CHOL" or atom.resname == "DPPC" or atom.resname == "DUPC": diff --git a/package/examples/nativecontacts.py b/package/examples/nativecontacts.py index 93585eb89b9..1432aaedd7f 100755 --- a/package/examples/nativecontacts.py +++ b/package/examples/nativecontacts.py @@ -51,7 +51,7 @@ C = MDAnalysis.analysis.contacts.ContactAnalysis(PSF, DCD, targetdir="./output") C.run() -print "Data file was written to %r" % C.output_bz2 +print "Data file was written to {0!r}".format(C.output_bz2) if have_matplotlib: matplotlib.rc('font', size=14) diff --git a/package/examples/radial_distribution_function.py b/package/examples/radial_distribution_function.py index c4528e2a1db..da0fd4188ef 100755 --- a/package/examples/radial_distribution_function.py +++ b/package/examples/radial_distribution_function.py @@ -57,11 +57,11 @@ n = solvent.numberOfAtoms() dist = np.zeros((n * (n - 1) / 2,), dtype=np.float64) -print "Start: n = %d, size of dist = %d " % (n, len(dist)) +print "Start: n = {0:d}, size of dist = {1:d} ".format(n, len(dist)) boxvolume = 0 for ts in universe.trajectory: - print "Frame %4d" % ts.frame + print "Frame {0:4d}".format(ts.frame) boxvolume += ts.volume # correct unitcell volume coor = solvent.coordinates() # periodicity is NOT handled correctly in this example because @@ -92,8 +92,8 @@ outfile = './output/rdf.dat' with open(outfile, 'w') as output: for radius, gofr in izip(radii, rdf): - output.write("%(radius)8.3f \t %(gofr)8.3f\n" % vars()) -print "g(r) data written to %(outfile)r" % vars() + output.write("{radius:8.3f} \t {gofr:8.3f}\n".format(**vars())) +print "g(r) data written to {outfile!r}".format(**vars()) if have_matplotlib: matplotlib.rc('font', size=14) diff --git a/package/examples/rmsd.py b/package/examples/rmsd.py index 8b589f233ee..496b24c77ff 100755 --- a/package/examples/rmsd.py +++ b/package/examples/rmsd.py @@ -61,7 +61,7 @@ def rmsd_traj(traj, ref, **kwargs): b = traj_coordinates.T.astype('float64') rmsd[k] = qcp.CalcRMSDRotationalMatrix(a, b, natoms, R, None) - print "%5d %8.3f A" % (k, rmsd[k]) + print "{0:5d} {1:8.3f} A".format(k, rmsd[k]) ### only comment in if you want to manipulate or write out ### the fitted trajectory @@ -83,15 +83,15 @@ def rmsd_traj(traj, ref, **kwargs): ref = Universe(PSF, PDB_small) # reference structure 4AKE trj = Universe(PSF, DCD) # trajectory of change 1AKE->4AKE - print "CA RMSD for %(DCD)r versus %(PDB_small)r" % vars() + print "CA RMSD for {DCD!r} versus {PDB_small!r}".format(**vars()) rmsds1 = rmsd_traj(trj, ref, select='name CA') - print "CA RMSD for %(DCD)r versus first frame" % vars() + print "CA RMSD for {DCD!r} versus first frame".format(**vars()) ref = Universe(PSF, DCD) ref.trajectory[0] # go to first frame rmsds2 = rmsd_traj(trj, ref, select='name CA') - print "CA RMSD for %(DCD)r versus last frame" % vars() + print "CA RMSD for {DCD!r} versus last frame".format(**vars()) ref = Universe(PSF, DCD) ref.trajectory[-1] # go to last frame rmsds3 = rmsd_traj(trj, ref, select='name CA') diff --git a/package/examples/schlitter_quasiharmonic.py b/package/examples/schlitter_quasiharmonic.py index 47112018410..176b8c16c1e 100755 --- a/package/examples/schlitter_quasiharmonic.py +++ b/package/examples/schlitter_quasiharmonic.py @@ -46,7 +46,7 @@ real = [e.real / 100. for e in eigenv] f = open('eigenval.dat', 'w') for i, val in enumerate(real): - f.write("%i\t%s\n" % (i + 1, val)) + f.write("{0:d}\t{1!s}\n".format(i + 1, val)) f.close() eigenval = eigenv * 1.6605402e-27 * 1e-20 diff --git a/package/setup.py b/package/setup.py index 29d6ff4105f..29e04e26df3 100755 --- a/package/setup.py +++ b/package/setup.py @@ -54,8 +54,8 @@ # Make sure I have the right Python version. if sys.version_info[:2] < (2, 7): - print('MDAnalysis requires Python 2.7 or better. Python %d.%d detected' % - sys.version_info[:2]) + print('MDAnalysis requires Python 2.7 or better. Python {0:d}.{1:d} detected'.format(* + sys.version_info[:2])) print('Please upgrade your version of Python.') sys.exit(-1) @@ -188,9 +188,9 @@ def hasfunction(cc, funcname, include=None, extra_postargs=None): fname = os.path.join(tmpdir, 'funcname.c') with open(fname, 'w') as f: if include is not None: - f.write('#include %s\n' % include) + f.write('#include {0!s}\n'.format(include)) f.write('int main(void) {\n') - f.write(' %s;\n' % funcname) + f.write(' {0!s};\n'.format(funcname)) f.write('}\n') # Redirect stderr to /dev/null to hide any error messages # from the compiler. diff --git a/testsuite/MDAnalysisTests/analysis/test_align.py b/testsuite/MDAnalysisTests/analysis/test_align.py index 930a84125e2..ca23dc680fe 100644 --- a/testsuite/MDAnalysisTests/analysis/test_align.py +++ b/testsuite/MDAnalysisTests/analysis/test_align.py @@ -82,7 +82,7 @@ def _assert_rmsd(self, fitted, frame, desired): fitted.trajectory[frame] rmsd = MDAnalysis.analysis.rms.rmsd(self.reference.atoms.coordinates(), fitted.atoms.coordinates()) assert_almost_equal(rmsd, desired, decimal=5, - err_msg="frame %d of fit does not have expected RMSD" % frame) + err_msg="frame {0:d} of fit does not have expected RMSD".format(frame)) @attr('issue') def test_alignto_checks_selections(self): diff --git a/testsuite/MDAnalysisTests/coordinates/base.py b/testsuite/MDAnalysisTests/coordinates/base.py index f3df4ba9a38..461c2d4487c 100644 --- a/testsuite/MDAnalysisTests/coordinates/base.py +++ b/testsuite/MDAnalysisTests/coordinates/base.py @@ -32,7 +32,7 @@ def test_flag_permissive_pdb_reader(self): def test_load_file(self): U = self.universe assert_equal(len(U.atoms), self.ref_n_atoms, - "load Universe from file %s" % U.trajectory.filename) + "load Universe from file {0!s}".format(U.trajectory.filename)) assert_equal(U.atoms.select_atoms('resid 150 and name HA2').atoms[0], U.atoms[self.ref_E151HA2_index], "Atom selections") diff --git a/testsuite/MDAnalysisTests/coordinates/test_coordinates.py b/testsuite/MDAnalysisTests/coordinates/test_coordinates.py index cfb0099ca39..6f97d688f60 100644 --- a/testsuite/MDAnalysisTests/coordinates/test_coordinates.py +++ b/testsuite/MDAnalysisTests/coordinates/test_coordinates.py @@ -98,8 +98,7 @@ def test_iteration(self): pass # just forward to last frame assert_equal( self.trajectory.n_frames - 1, ts.frame, - "iteration yielded wrong number of frames (%d), should be %d" % - (ts.frame, self.trajectory.n_frames)) + "iteration yielded wrong number of frames ({0:d}), should be {1:d}".format(ts.frame, self.trajectory.n_frames)) def test_jump_lastframe_trajectory(self): self.trajectory[-1] @@ -152,7 +151,7 @@ def test_write_dcd(self): ts_orig._pos, ts_new._pos, self.prec, - err_msg="Coordinates disagree at frame %d" % ts_orig.frame) + err_msg="Coordinates disagree at frame {0:d}".format(ts_orig.frame)) class TestChainReaderCommonDt(TestCase): @@ -171,7 +170,7 @@ def test_time(self): assert_almost_equal(self.trajectory.time, self.trajectory.frame*self.common_dt, 5, - err_msg="Wrong time for frame %d" % frame_n ) + err_msg="Wrong time for frame {0:d}".format(frame_n) ) class TestChainReaderFormats(TestCase): diff --git a/testsuite/MDAnalysisTests/coordinates/test_dcd.py b/testsuite/MDAnalysisTests/coordinates/test_dcd.py index bbac53204fa..ce2252bcf67 100644 --- a/testsuite/MDAnalysisTests/coordinates/test_dcd.py +++ b/testsuite/MDAnalysisTests/coordinates/test_dcd.py @@ -306,16 +306,16 @@ def test_OtherWriter(self): dcd.atoms.coordinates(), xtc.atoms.coordinates(), 2, - err_msg="DCD -> XTC: coordinates are messed up (frame %d)" % - dcd.trajectory.frame) + err_msg="DCD -> XTC: coordinates are messed up (frame {0:d})".format( + dcd.trajectory.frame)) xtc.trajectory[3] dcd.trajectory[3] assert_array_almost_equal( dcd.atoms.coordinates(), xtc.atoms.coordinates(), 2, - err_msg="DCD -> XTC: coordinates are messed up (frame %d)" % - dcd.trajectory.frame) + err_msg="DCD -> XTC: coordinates are messed up (frame {0:d})".format( + dcd.trajectory.frame)) class _TestDCDReader_TriclinicUnitcell(TestCase): @@ -402,8 +402,8 @@ def test_unitcell(self): ts_orig.dimensions, ts_copy.dimensions, 3, - err_msg="NCDF->DCD: unit cell dimensions wrong at frame %d" % - ts_orig.frame) + err_msg="NCDF->DCD: unit cell dimensions wrong at frame {0:d}".format( + ts_orig.frame)) def test_coordinates(self): for ts_orig, ts_copy in zip(self.u.trajectory, @@ -412,8 +412,8 @@ def test_coordinates(self): self.u.atoms.positions, self.w.atoms.positions, 3, - err_msg="NCDF->DCD: coordinates wrong at frame %d" % - ts_orig.frame) + err_msg="NCDF->DCD: coordinates wrong at frame {0:d}".format( + ts_orig.frame)) class TestDCDCorrel(_TestDCD): diff --git a/testsuite/MDAnalysisTests/coordinates/test_trz.py b/testsuite/MDAnalysisTests/coordinates/test_trz.py index 5d32c742564..352eecea3a8 100644 --- a/testsuite/MDAnalysisTests/coordinates/test_trz.py +++ b/testsuite/MDAnalysisTests/coordinates/test_trz.py @@ -167,7 +167,7 @@ def _copy_traj(self, writer): for att in orig_ts.data: assert_array_almost_equal(orig_ts.data[att], written_ts.data[att], self.prec, - err_msg="TS equal failed for %s" % att) + err_msg="TS equal failed for {0!s}".format(att)) class TestTRZWriter2(object): diff --git a/testsuite/MDAnalysisTests/coordinates/test_xdr.py b/testsuite/MDAnalysisTests/coordinates/test_xdr.py index 6c70bc37c7c..1afe2601f15 100644 --- a/testsuite/MDAnalysisTests/coordinates/test_xdr.py +++ b/testsuite/MDAnalysisTests/coordinates/test_xdr.py @@ -292,8 +292,8 @@ def test_velocities(self): self.universe.atoms[index].velocity, v_known, self.prec, - err_msg="atom[%d].velocity does not match known values" % - index) + err_msg="atom[{0:d}].velocity does not match known values".format( + index)) class _XDRNoConversion(TestCase): @@ -520,7 +520,7 @@ def _single_frame(self, filename): w.atoms.coordinates(), u.atoms.coordinates(), self.prec, - err_msg="coordinates do not match for %r" % filename) + err_msg="coordinates do not match for {0!r}".format(filename)) class TestXTCWriterSingleFrame(_GromacsWriterIssue101): diff --git a/testsuite/MDAnalysisTests/test_atomgroup.py b/testsuite/MDAnalysisTests/test_atomgroup.py index 21ac967cc1e..0c55090427e 100644 --- a/testsuite/MDAnalysisTests/test_atomgroup.py +++ b/testsuite/MDAnalysisTests/test_atomgroup.py @@ -1448,7 +1448,7 @@ def test_write_atoms(self): self.universe.atoms.write(self.outfile) u2 = self.universe_from_tmp() assert_array_almost_equal(self.universe.atoms.coordinates(), u2.atoms.coordinates(), self.precision, - err_msg="atom coordinate mismatch between original and %s file" % self.ext) + err_msg="atom coordinate mismatch between original and {0!s} file".format(self.ext)) def test_write_empty_atomgroup(self): sel = self.universe.select_atoms('name doesntexist') diff --git a/testsuite/ez_setup.py b/testsuite/ez_setup.py index 7fd06b38ef6..37c7d879895 100644 --- a/testsuite/ez_setup.py +++ b/testsuite/ez_setup.py @@ -95,8 +95,7 @@ def _build_egg(egg, tarball, to_dir): def _do_download(version, download_base, to_dir, download_delay): - egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg' - % (version, sys.version_info[0], sys.version_info[1])) + egg = os.path.join(to_dir, 'setuptools-{0!s}-py{1:d}.{2:d}.egg'.format(version, sys.version_info[0], sys.version_info[1])) if not os.path.exists(egg): tarball = download_setuptools(version, download_base, to_dir, download_delay) @@ -154,7 +153,7 @@ def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, from urllib.request import urlopen except ImportError: from urllib2 import urlopen - tgz_name = "setuptools-%s.tar.gz" % version + tgz_name = "setuptools-{0!s}.tar.gz".format(version) url = download_base + tgz_name saveto = os.path.join(to_dir, tgz_name) src = dst = None @@ -219,7 +218,7 @@ def sorter(dir1, dir2): if self.errorlevel > 1: raise else: - self._dbg(1, "tarfile: %s" % e) + self._dbg(1, "tarfile: {0!s}".format(e)) def _build_install_args(options): diff --git a/testsuite/setup.py b/testsuite/setup.py index 1cbd6c49890..9edebf60939 100755 --- a/testsuite/setup.py +++ b/testsuite/setup.py @@ -56,8 +56,8 @@ # Make sure I have the right Python version. if sys.version_info[:2] < (2, 6): - print("MDAnalysis requires Python 2.6 or better. Python %d.%d detected" % - sys.version_info[:2]) + print("MDAnalysis requires Python 2.6 or better. Python {0:d}.{1:d} detected".format(* + sys.version_info[:2])) print("Please upgrade your version of Python.") sys.exit(-1) @@ -136,7 +136,7 @@ classifiers=CLASSIFIERS, long_description=LONG_DESCRIPTION, install_requires=[ - 'MDAnalysis==%s' % RELEASE, # same as this release! + 'MDAnalysis=={0!s}'.format(RELEASE), # same as this release! 'numpy>=1.5', 'nose>=1.3.7', 'tempdir', From 39c969e18e160208e3b56dce3e1cd14a59165ecf Mon Sep 17 00:00:00 2001 From: Jonathan Barnoud Date: Wed, 16 Dec 2015 06:49:14 +0100 Subject: [PATCH 2/2] Remove some bangs from formated string Cody (quantifiedcode) uses exclamation marks in its format srtings. Some appear to cause error. --- package/MDAnalysis/analysis/align.py | 2 +- package/MDAnalysis/coordinates/XYZ.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package/MDAnalysis/analysis/align.py b/package/MDAnalysis/analysis/align.py index 66eecb277c0..c5f7d075be0 100644 --- a/package/MDAnalysis/analysis/align.py +++ b/package/MDAnalysis/analysis/align.py @@ -922,7 +922,7 @@ 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("{0:4!s} {1:3d} {2:3!s} {3:3!s} {4:6.3f} | {5:4!s} {6:3d} {7:3!s} {8:3!s} {9:6.3f}".format(ar.segid, ar.resid, ar.resname, ar.name, ar.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) diff --git a/package/MDAnalysis/coordinates/XYZ.py b/package/MDAnalysis/coordinates/XYZ.py index 6b9bcfcbf88..cdb4daeeb2f 100644 --- a/package/MDAnalysis/coordinates/XYZ.py +++ b/package/MDAnalysis/coordinates/XYZ.py @@ -246,7 +246,7 @@ def write_next_timestep(self, ts=None): self._xyz.write("{0:d}\n".format(ts.n_atoms)) self._xyz.write("frame {0}\n".format(ts.frame)) for atom, (x, y, z) in itertools.izip(self.atomnames, coordinates): - self._xyz.write("{0:8!s} {1:10.5f} {2:10.5f} {3:10.5f}\n".format(atom, x, y, z)) + self._xyz.write("{0:8s} {1:10.5f} {2:10.5f} {3:10.5f}\n".format(atom, x, y, z)) class XYZReader(base.Reader):