Skip to content

Commit

Permalink
fmt selections (#4861)
Browse files Browse the repository at this point in the history
  • Loading branch information
RMeli authored Dec 24, 2024
1 parent f855022 commit 55cce24
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 30 deletions.
6 changes: 4 additions & 2 deletions package/MDAnalysis/selections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ def get_writer(filename: str, defaultformat: str) -> base.SelectionWriterBase:
try:
return _SELECTION_WRITERS[format]
except KeyError:
errmsg = (f"Writing as {format} is not implemented; only "
f"{ _SELECTION_WRITERS.keys()} will work.")
errmsg = (
f"Writing as {format} is not implemented; only "
f"{ _SELECTION_WRITERS.keys()} will work."
)
raise NotImplementedError(errmsg) from None
35 changes: 21 additions & 14 deletions package/MDAnalysis/selections/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class _Selectionmeta(type):
def __init__(cls, name, bases, classdict):
type.__init__(type, name, bases, classdict)
try:
fmt = util.asiterable(classdict['format'])
fmt = util.asiterable(classdict["format"])
except KeyError:
pass
else:
Expand Down Expand Up @@ -97,17 +97,20 @@ class SelectionWriterBase(metaclass=_Selectionmeta):
and closed with the :meth:`close` method or when exiting the `with`
statement.
"""

#: Name of the format.
format = None
#: Extension of output files.
ext = None
#: Special character to continue a line across a newline.
continuation = ''
continuation = ""
#: Comment format string; should contain '%s' or ``None`` for no comments.
commentfmt = None
default_numterms = 8

def __init__(self, filename, mode="w", numterms=None, preamble=None, **kwargs):
def __init__(
self, filename, mode="w", numterms=None, preamble=None, **kwargs
):
"""Set up for writing to *filename*.
Parameters
Expand All @@ -126,8 +129,10 @@ def __init__(self, filename, mode="w", numterms=None, preamble=None, **kwargs):
use as defaults for :meth:`write`
"""
self.filename = util.filename(filename, ext=self.ext)
if not mode in ('a', 'w'):
raise ValueError("mode must be one of 'w', 'a', not {0!r}".format(mode))
if not mode in ("a", "w"):
raise ValueError(
"mode must be one of 'w', 'a', not {0!r}".format(mode)
)
self.mode = mode
self._current_mode = mode[0]
if numterms is None or numterms < 0:
Expand All @@ -154,8 +159,8 @@ def comment(self, s):
A newline is appended to non-empty strings.
"""
if self.commentfmt is None:
return ''
return self.commentfmt % s + '\n'
return ""
return self.commentfmt % s + "\n"

def write_preamble(self):
"""Write a header, depending on the file format."""
Expand Down Expand Up @@ -188,7 +193,7 @@ def write(self, selection, number=None, name=None, frame=None, mode=None):
frame = u.trajectory.ts.frame
except AttributeError:
frame = 1 # should catch cases when we are analyzing a single PDB (?)
name = name or self.otherargs.get('name', None)
name = name or self.otherargs.get("name", None)
if name is None:
if number is None:
self.number += 1
Expand All @@ -203,13 +208,15 @@ def write(self, selection, number=None, name=None, frame=None, mode=None):
out = self._outfile
self._write_head(out, name=name)
for iatom in range(0, len(selection.atoms), step):
line = selection_terms[iatom:iatom + step]
line = selection_terms[iatom : iatom + step]
out.write(" ".join(line))
if len(line) == step and not iatom + step == len(selection.atoms):
out.write(' ' + self.continuation + '\n')
out.write(' ') # safe so that we don't have to put a space at the start of tail
out.write(" " + self.continuation + "\n")
out.write(
" "
) # safe so that we don't have to put a space at the start of tail
self._write_tail(out)
out.write('\n') # always terminate with newline
out.write("\n") # always terminate with newline

def close(self):
"""Close the file
Expand All @@ -234,11 +241,11 @@ def _translate(self, atoms, **kwargs):

def _write_head(self, out, **kwargs):
"""Initial output to open file object *out*."""
pass # pylint: disable=unnecessary-pass
pass # pylint: disable=unnecessary-pass

def _write_tail(self, out, **kwargs):
"""Last output to open file object *out*."""
pass # pylint: disable=unnecessary-pass
pass # pylint: disable=unnecessary-pass

# Context manager support to match Coordinate writers
# all file handles use a with block in their write method, so these do nothing special
Expand Down
16 changes: 11 additions & 5 deletions package/MDAnalysis/selections/charmm.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
Expand Down Expand Up @@ -45,20 +45,26 @@
class SelectionWriter(base.SelectionWriterBase):
format = ["CHARMM", "str"]
ext = "str"
continuation = '-'
continuation = "-"
commentfmt = "! %s"
default_numterms = 4 # be conservative because CHARMM only reads 72 columns
default_numterms = (
4 # be conservative because CHARMM only reads 72 columns
)

def _translate(self, atoms, **kwargs):
# CHARMM index is 1-based
def _index(atom):
return "BYNUM {0:d}".format((atom.index + 1))

return base.join(atoms, ' .or.', _index)
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 ".format(**kwargs) + self.continuation + '\n')
out.write(
"DEFINE {name!s} SELECT ".format(**kwargs)
+ self.continuation
+ "\n"
)

def _write_tail(self, out, **kwargs):
out.write("END")
2 changes: 1 addition & 1 deletion package/MDAnalysis/selections/gromacs.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
Expand Down
6 changes: 3 additions & 3 deletions package/MDAnalysis/selections/jmol.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
Expand Down Expand Up @@ -46,14 +46,14 @@ class SelectionWriter(base.SelectionWriterBase):
format = ["Jmol", "spt"]
ext = "spt"
default_numterms = None
commentfmt = '#'
commentfmt = "#"

def _translate(self, atoms, **kwargs):
# Jmol indexing is 0 based when using atom bitsets
def _index(atom):
return str(atom.index)

return base.join(atoms, ' ', _index)
return base.join(atoms, " ", _index)

def _write_head(self, out, **kwargs):
out.write("@~{name!s} ({{".format(**kwargs))
Expand Down
10 changes: 6 additions & 4 deletions package/MDAnalysis/selections/pymol.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
Expand Down Expand Up @@ -46,7 +46,7 @@
class SelectionWriter(base.SelectionWriterBase):
format = ["PyMol", "pml"]
ext = "pml"
continuation = '\\' # quoted backslash!
continuation = "\\" # quoted backslash!
commentfmt = "# %s"
default_numterms = 6

Expand All @@ -55,8 +55,10 @@ def _translate(self, atoms, **kwargs):
def _index(atom):
return "index {0:d}".format((atom.index + 1))

return base.join(atoms, ' |', _index)
return base.join(atoms, " |", _index)

def _write_head(self, out, **kwargs):
out.write(self.comment("MDAnalysis PyMol selection"))
out.write("select {name!s}, ".format(**kwargs) + self.continuation + '\n')
out.write(
"select {name!s}, ".format(**kwargs) + self.continuation + "\n"
)
2 changes: 1 addition & 1 deletion package/MDAnalysis/selections/vmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
class SelectionWriter(base.SelectionWriterBase):
format = "VMD"
ext = "vmd"
continuation = '\\'
continuation = "\\"
commentfmt = "# %s"

def _write_head(self, out, **kwargs):
Expand Down
1 change: 1 addition & 0 deletions package/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ tables\.py
| MDAnalysis/lib/.*\.py^
| MDAnalysis/transformations/.*\.py
| MDAnalysis/converters/.*\.py
| MDAnalysis/selections/.*\.py
)
'''
extend-exclude = '''
Expand Down

0 comments on commit 55cce24

Please sign in to comment.