Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[fmt] Selections #4861

Merged
merged 1 commit into from
Dec 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
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 @@
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 @@
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 @@
A newline is appended to non-empty strings.
"""
if self.commentfmt is None:
return ''
return self.commentfmt % s + '\n'
return ""

Check warning on line 162 in package/MDAnalysis/selections/base.py

View check run for this annotation

Codecov / codecov/patch

package/MDAnalysis/selections/base.py#L162

Added line #L162 was not covered by tests
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 @@
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 @@
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 _write_head(self, out, **kwargs):
"""Initial output to open file object *out*."""
pass # pylint: disable=unnecessary-pass
pass # pylint: disable=unnecessary-pass

Check warning on line 244 in package/MDAnalysis/selections/base.py

View check run for this annotation

Codecov / codecov/patch

package/MDAnalysis/selections/base.py#L244

Added line #L244 was not covered by tests

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
Loading