diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 8a8a1440392..de7749e2788 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -55,9 +55,6 @@ style: - git submodule deinit . script: - maintainer/CI/fix_style.sh - - git --no-pager diff > style.patch - - git diff-index --quiet HEAD -- || (echo "Failed style check. Download $CI_JOB_URL/artifacts/raw/style.patch to see which changes are necessary." && exit 1) - - echo "Passed style check" tags: - docker - linux @@ -72,7 +69,7 @@ style: style_doxygen: <<: *global_job_definition stage: prepare - image: gitlab.icp.uni-stuttgart.de:4567/espressomd/docker/ubuntu-python3:cuda-9.0 + image: gitlab.icp.uni-stuttgart.de:4567/espressomd/docker/ubuntu-python3:cuda-10.1 dependencies: [] script: - mkdir build diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 00000000000..40862e285bc --- /dev/null +++ b/.pylintrc @@ -0,0 +1,503 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-whitelist= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS build + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=2 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Specify a configuration file. +#rcfile= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=all + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=dangerous-default-value, # W0102 + wildcard-import, # W0401 + unused-import, # W0611 + unused-variable, # W0612 + unused-argument, # W0613 + unused-wildcard-import, # W0614 + deprecated-method, # W1505 + cyclic-import, # R0401 + trailing-comma-tuple, # R1707 + bad-classmethod-argument, # C0202 + undefined-variable, # E0602 + + +[REPORTS] + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=no + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: de (aspell), de_AT +# (aspell), de_CH (aspell), de_DE (aspell), en (aspell), en_AU (aspell), en_CA +# (aspell), en_GB (aspell), en_US (aspell).. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma, + dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[LOGGING] + +# Format style used to check logging format string. `old` means using % +# formatting, while `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[STRING] + +# This flag controls whether the implicit-str-concat-in-sequence should +# generate a warning on implicit string concatenation in sequences defined over +# several lines. +check-str-concat-over-line-jumps=no + + +[IMPORTS] + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules=optparse,tkinter.tix + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled). +ext-import-graph= + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled). +import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[DESIGN] + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement. +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/doc/doxygen/gen_doxyconfig.py b/doc/doxygen/gen_doxyconfig.py index 6fa8017e153..fcd4190f13c 100755 --- a/doc/doxygen/gen_doxyconfig.py +++ b/doc/doxygen/gen_doxyconfig.py @@ -19,7 +19,6 @@ # # This script generates the file doxy-features # -import inspect import sys import os diff --git a/doc/tutorials/02-charged_system/scripts/nacl_units_confined_vis.py b/doc/tutorials/02-charged_system/scripts/nacl_units_confined_vis.py index 788d31ee7be..8af9e379e32 100644 --- a/doc/tutorials/02-charged_system/scripts/nacl_units_confined_vis.py +++ b/doc/tutorials/02-charged_system/scripts/nacl_units_confined_vis.py @@ -24,7 +24,6 @@ from espressomd import visualization_opengl import numpy from threading import Thread -from time import sleep assert_features(["ELECTROSTATICS", "MASS", "LENNARD_JONES"]) diff --git a/doc/tutorials/02-charged_system/scripts/nacl_units_vis.py b/doc/tutorials/02-charged_system/scripts/nacl_units_vis.py index 83c0b366509..c00ec2d95c6 100644 --- a/doc/tutorials/02-charged_system/scripts/nacl_units_vis.py +++ b/doc/tutorials/02-charged_system/scripts/nacl_units_vis.py @@ -23,7 +23,6 @@ from espressomd import visualization_opengl import numpy from threading import Thread -from time import sleep assert_features(["ELECTROSTATICS", "MASS", "LENNARD_JONES"]) @@ -156,7 +155,7 @@ def main(): print("\n--->Temperature Equilibration") system.time = 0.0 - for i in range(num_steps_equilibration): + for _ in range(num_steps_equilibration): energy = system.analysis.energy() temp_measured = energy['kinetic'] / ((3.0 / 2.0) * n_part) print("t={0:.1f}, E_total={1:.2f}, E_coulomb={2:.2f}, T_cur={3:.4f}" diff --git a/doc/tutorials/04-lattice_boltzmann/scripts/04-lattice_boltzmann_part3_solution.py b/doc/tutorials/04-lattice_boltzmann/scripts/04-lattice_boltzmann_part3_solution.py index 48616f80f1b..b1a0f0e31ad 100644 --- a/doc/tutorials/04-lattice_boltzmann/scripts/04-lattice_boltzmann_part3_solution.py +++ b/doc/tutorials/04-lattice_boltzmann/scripts/04-lattice_boltzmann_part3_solution.py @@ -18,8 +18,6 @@ import logging import numpy as np logging.basicConfig(level=logging.INFO) -import matplotlib.pyplot as plt -import scipy import espressomd espressomd.assert_features(['LENNARD_JONES']) @@ -123,4 +121,5 @@ tau = corrdata[1:, 0] msd = corrdata[1:, 2] + corrdata[1:, 3] + corrdata[1:, 4] np.save('msd_{}'.format(N), np.c_[tau, msd]) + np.save('rh.npy', rh_results) diff --git a/doc/tutorials/06-active_matter/EXERCISES/enhanced_diffusion.py b/doc/tutorials/06-active_matter/EXERCISES/enhanced_diffusion.py index cba569769e8..af496e3c280 100644 --- a/doc/tutorials/06-active_matter/EXERCISES/enhanced_diffusion.py +++ b/doc/tutorials/06-active_matter/EXERCISES/enhanced_diffusion.py @@ -24,13 +24,10 @@ import numpy as np import os -import sys import argparse -import time import espressomd -from espressomd import assert_features -from espressomd.observables import ParticlePositions, ParticleVelocities, ParticleAngularVelocities +from espressomd.observables import ParticlePositions, ParticleVelocities, ParticleAngularVelocities # pylint: disable=unused-import from espressomd.accumulators import Correlator espressomd.assert_features( diff --git a/doc/tutorials/06-active_matter/EXERCISES/flow_field.py b/doc/tutorials/06-active_matter/EXERCISES/flow_field.py index d56a14bee13..1bca345b716 100644 --- a/doc/tutorials/06-active_matter/EXERCISES/flow_field.py +++ b/doc/tutorials/06-active_matter/EXERCISES/flow_field.py @@ -22,13 +22,15 @@ # ########################################################################## -import numpy as np import os import espressomd from espressomd import assert_features, lb +assert_features(["ENGINE", "CUDA", "MASS", "ROTATION", "ROTATIONAL_INERTIA"]) + + ## Exercise 1 ## # Create a routine to read in the hydrodynamic type # (pusher/puller) and position at which the particle diff --git a/doc/tutorials/06-active_matter/EXERCISES/rectification_geometry.py b/doc/tutorials/06-active_matter/EXERCISES/rectification_geometry.py index 5b418b87b4a..9720a860ebc 100644 --- a/doc/tutorials/06-active_matter/EXERCISES/rectification_geometry.py +++ b/doc/tutorials/06-active_matter/EXERCISES/rectification_geometry.py @@ -25,7 +25,6 @@ from math import cos, pi, sin import numpy as np import os -import sys import espressomd espressomd.assert_features(["CUDA", "LB_BOUNDARIES_GPU"]) @@ -44,15 +43,15 @@ LENGTH = 100 DIAMETER = 20 -padding = 2 +PADDING = 2 TIME_STEP = 0.01 # Setup the MD parameters BOX_L = np.array( - [LENGTH + 2 * padding, - DIAMETER + 2 * padding, - DIAMETER + 2 * padding]) + [LENGTH + 2 * PADDING, + DIAMETER + 2 * PADDING, + DIAMETER + 2 * PADDING]) system = espressomd.System(box_l=BOX_L) system.cell_system.skin = 0.1 system.time_step = TIME_STEP diff --git a/doc/tutorials/06-active_matter/EXERCISES/rectification_simulation.py b/doc/tutorials/06-active_matter/EXERCISES/rectification_simulation.py index f262e33a100..7a3686b7e90 100644 --- a/doc/tutorials/06-active_matter/EXERCISES/rectification_simulation.py +++ b/doc/tutorials/06-active_matter/EXERCISES/rectification_simulation.py @@ -22,10 +22,9 @@ # ########################################################################## -from math import cos, pi, sin +from math import cos, pi, sin # pylint: disable=unused-import import numpy as np import os -import sys import argparse import espressomd @@ -33,6 +32,9 @@ from espressomd.shapes import Cylinder, Wall, HollowCone +assert_features(["ENGINE", "LENNARD_JONES", "ROTATION", "MASS"]) + + # Quaternion procedure def a2quat(phi, theta): diff --git a/doc/tutorials/06-active_matter/SOLUTIONS/enhanced_diffusion.py b/doc/tutorials/06-active_matter/SOLUTIONS/enhanced_diffusion.py index b4100af3232..0a7caa8419e 100644 --- a/doc/tutorials/06-active_matter/SOLUTIONS/enhanced_diffusion.py +++ b/doc/tutorials/06-active_matter/SOLUTIONS/enhanced_diffusion.py @@ -24,12 +24,9 @@ import numpy as np import os -import sys import argparse -import time import espressomd -from espressomd import assert_features from espressomd.observables import ParticlePositions, ParticleVelocities, ParticleAngularVelocities from espressomd.accumulators import Correlator @@ -115,8 +112,7 @@ for i in range(SAMP_STEPS): if (i + 1) % 100 == 0: print('\rrun %i: %.0f%%' % (run + 1, (i + 1) * 100. / SAMP_STEPS), - end='') - sys.stdout.flush() + end='', flush=True) system.integrator.run(SAMP_LENGTH) print() diff --git a/doc/tutorials/06-active_matter/SOLUTIONS/flow_field.py b/doc/tutorials/06-active_matter/SOLUTIONS/flow_field.py index 74406b227c6..2f5e3059ef4 100644 --- a/doc/tutorials/06-active_matter/SOLUTIONS/flow_field.py +++ b/doc/tutorials/06-active_matter/SOLUTIONS/flow_field.py @@ -22,7 +22,6 @@ # ########################################################################## -import numpy as np import os import sys import argparse diff --git a/doc/tutorials/06-active_matter/SOLUTIONS/rectification_geometry.py b/doc/tutorials/06-active_matter/SOLUTIONS/rectification_geometry.py index 369f6d55d42..121ce59ddf2 100644 --- a/doc/tutorials/06-active_matter/SOLUTIONS/rectification_geometry.py +++ b/doc/tutorials/06-active_matter/SOLUTIONS/rectification_geometry.py @@ -25,11 +25,10 @@ from math import cos, pi, sin import numpy as np import os -import sys import espressomd espressomd.assert_features(["CUDA", "LB_BOUNDARIES_GPU"]) -from espressomd import assert_features, lb +from espressomd import lb from espressomd.lbboundaries import LBBoundary from espressomd.shapes import Cylinder, Wall, HollowCone @@ -39,8 +38,8 @@ outdir = "./RESULTS_RECTIFICATION" os.makedirs(outdir, exist_ok=True) -# Setup the box (we pad the diameter to ensure that the LB boundaries -# and therefore the constraints, are away from the edge of the box) +# Setup the box (we pad the geometry to make sure +# the LB boundaries are away from the edges of the box) LENGTH = 100 DIAMETER = 20 diff --git a/doc/tutorials/06-active_matter/SOLUTIONS/rectification_simulation.py b/doc/tutorials/06-active_matter/SOLUTIONS/rectification_simulation.py index 072db3f7642..09e6620eed7 100644 --- a/doc/tutorials/06-active_matter/SOLUTIONS/rectification_simulation.py +++ b/doc/tutorials/06-active_matter/SOLUTIONS/rectification_simulation.py @@ -25,7 +25,6 @@ from math import cos, pi, sin import numpy as np import os -import sys import argparse import espressomd @@ -35,8 +34,8 @@ assert_features(["ENGINE", "LENNARD_JONES", "ROTATION", "MASS"]) -# Quaternion procedure +# Quaternion procedure def a2quat(phi, theta): @@ -192,8 +191,8 @@ def a2quat(phi, theta): system.time = 0. for i in range(PROD_STEPS): if (i + 1) % 5 == 0: - print('\rprogress: %.0f%%' % ((i + 1) * 100. / PROD_STEPS), end='') - sys.stdout.flush() + print('\rprogress: %.0f%%' % ((i + 1) * 100. / PROD_STEPS), + end='', flush=True) # We output the coordinate of the center of mass in # the direction of the long axis, here we consider diff --git a/doc/tutorials/07-electrokinetics/scripts/eof_analytical.py b/doc/tutorials/07-electrokinetics/scripts/eof_analytical.py index 819def057a0..438a112a4ea 100644 --- a/doc/tutorials/07-electrokinetics/scripts/eof_analytical.py +++ b/doc/tutorials/07-electrokinetics/scripts/eof_analytical.py @@ -99,7 +99,6 @@ def solve(xi=None, d=None, bjerrum_length=None, sigma=None, valency=None): def density(x=None, xi=None, bjerrum_length=None): - kb = 1.0 return (xi**2) / (2.0 * np.pi * bjerrum_length * np.cos(xi * x)**2) # function to calculate the velocity @@ -117,19 +116,6 @@ def pressure_tensor_offdiagonal(x=None, xi=None, bjerrum_length=None, force=None): return force * xi * np.tan(xi * x) / (2.0 * np.pi * bjerrum_length) -# function to calculate the hydrostatic pressure - -# Technically, the LB simulates a compressible fluid, whose pressure -# tensor contains an additional term on the diagonal, proportional to -# the divergence of the velocity. We neglect this (small) contribution. -# The LB pressure tensor also contains the convective acceleration, which -# we neglect here. - - -def hydrostatic_pressure(x=None, xi=None, bjerrum_length=None, - tensor_entry=None): - return 0.0 - position_list = [] density_list = [] diff --git a/maintainer/CI/doc_warnings.sh b/maintainer/CI/doc_warnings.sh index 4882a740035..7dd5c02ab79 100755 --- a/maintainer/CI/doc_warnings.sh +++ b/maintainer/CI/doc_warnings.sh @@ -108,7 +108,7 @@ if [ $? = "0" ]; then fi if [ "${CI}" != "" ]; then - "${srcdir}/maintainer/gh_post_docs_warnings.py" sphinx ${n_warnings} doc_warnings.log + "${srcdir}/maintainer/gh_post_docs_warnings.py" sphinx ${n_warnings} doc_warnings.log || exit 1 fi if [ ${n_warnings} = "0" ]; then diff --git a/maintainer/CI/dox_warnings.sh b/maintainer/CI/dox_warnings.sh index b3e2d6c85a9..9b786b302d4 100755 --- a/maintainer/CI/dox_warnings.sh +++ b/maintainer/CI/dox_warnings.sh @@ -80,7 +80,7 @@ fi cat dox_warnings.log if [ "${CI}" != "" ]; then - "${srcdir}/maintainer/gh_post_docs_warnings.py" doxygen ${n_warnings} dox_warnings.log + "${srcdir}/maintainer/gh_post_docs_warnings.py" doxygen ${n_warnings} dox_warnings.log || exit 1 fi if [ ${n_warnings} = "0" ]; then diff --git a/maintainer/CI/fix_style.sh b/maintainer/CI/fix_style.sh index fbc37b628b6..e9df7d9a767 100755 --- a/maintainer/CI/fix_style.sh +++ b/maintainer/CI/fix_style.sh @@ -49,6 +49,44 @@ find . \( -name '*.py' -o -name '*.pyx' -o -name '*.pxd' \) -not -path './libs/* find . -type f -executable ! -name '*.sh' ! -name '*.py' ! -name '*.sh.in' ! -name pypresso.cmakein -not -path './.git/*' | xargs -r -n 5 -P 8 chmod -x || exit 3 if [ "$CI" != "" ]; then - maintainer/gh_post_style_patch.py + git --no-pager diff > style.patch + maintainer/gh_post_style_patch.py || exit 1 +fi +git diff-index --quiet HEAD -- +if [ $? = 1 ]; then + if [ "$CI" != "" ]; then + echo "Failed style check. Download $CI_JOB_URL/artifacts/raw/style.patch to see which changes are necessary." >&2 + else + echo "Failed style check" >&2 + fi + exit 1 +else + echo "Passed style check" +fi + +pylint_command () { + if hash pylint 2> /dev/null; then + pylint "$@" + elif hash pylint3 2> /dev/null; then + pylint3 "$@" + elif hash pylint-3 2> /dev/null; then + pylint-3 "$@" + else + echo "pylint not found" >&2 + exit 1 + fi +} +pylint_command --score=no --reports=no --output-format=text src doc maintainer testsuite samples | tee pylint.log +errors=$(grep -P '^[a-z]+/.+?.py:[0-9]+:[0-9]+: [CRWEF][0-9]+:' pylint.log | wc -l) + +if [ "$CI" != "" ]; then + maintainer/gh_post_pylint.py ${errors} pylint.log || exit 1 +fi +if [ ${errors} != 0 ]; then + echo "Failed pylint check: ${errors} errors" >&2 + exit 1 +else + echo "Passed pylint check" fi +exit 0 diff --git a/maintainer/gh_post_docs_warnings.py b/maintainer/gh_post_docs_warnings.py index 26f0f4c307e..384a44e0e6d 100755 --- a/maintainer/gh_post_docs_warnings.py +++ b/maintainer/gh_post_docs_warnings.py @@ -34,12 +34,13 @@ doc_type, has_warnings, filepath_warnings = sys.argv[-3:] has_warnings = has_warnings != '0' prefix = {'sphinx': 'doc', 'doxygen': 'dox'}[doc_type] +TOKEN_ESPRESSO_CI = prefix + '_warnings.sh' # Delete all existing comments comments = requests.get(URL) for comment in comments.json(): - if comment['user']['login'] == 'espresso-ci' and prefix + \ - '_warnings.sh' in comment['body']: + if comment['user']['login'] == 'espresso-ci' and \ + TOKEN_ESPRESSO_CI in comment['body']: requests.delete(comment['url'] + '?access_token=' + os.environ['GITHUB_TOKEN']) @@ -72,5 +73,6 @@ '../maintainer/CI/{}_warnings.sh` using the maxset config. This is ' 'the same command that I have executed to generate the log above.' .format(doc_type, prefix)) + assert TOKEN_ESPRESSO_CI in comment requests.post(URL, json={'body': comment}) diff --git a/maintainer/gh_post_pylint.py b/maintainer/gh_post_pylint.py new file mode 100755 index 00000000000..9852f23b9b8 --- /dev/null +++ b/maintainer/gh_post_pylint.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2018-2019 The ESPResSo project +# +# This file is part of ESPResSo. +# +# ESPResSo is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# ESPResSo is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +import re +import os +import sys +import requests + +if not os.environ['CI_COMMIT_REF_NAME'].startswith('PR-'): + exit(0) + +PR = os.environ['CI_COMMIT_REF_NAME'][3:] +URL = 'https://api.github.com/repos/espressomd/espresso/issues/' + \ + PR + '/comments?access_token=' + os.environ['GITHUB_TOKEN'] +SIZELIMIT = 5000 +TOKEN_ESPRESSO_CI = 'Pylint summary' + +n_warnings, filepath_warnings = sys.argv[-2:] + +# Delete older pylint messages +comments = requests.get(URL) +for comment in comments.json(): + if comment['user']['login'] == 'espresso-ci' and \ + TOKEN_ESPRESSO_CI in comment['body']: + requests.delete(comment['url'] + '?access_token=' + + os.environ['GITHUB_TOKEN']) + +# If pylint raised errors, post a new comment +if n_warnings != '0': + with open(filepath_warnings) as f: + warnings = f.read().strip() + # the logfile must be guarded by backticks + backticks = max(['``'] + re.findall('`+', warnings), key=len) + '`' + assert len(backticks) < 12, 'cannot guard logfile warnings with backticks' + # format message + comment = 'Your pull request does not meet our code style rules. ' + comment += 'Pylint summary:\n' + backticks + '\n' + if len(warnings) > SIZELIMIT: + for line in warnings.split('\n'): + if len(comment) + len(line) > SIZELIMIT - 200: + break + comment += line + '\n' + comment = comment.rstrip() + '\n' + backticks + '\n' + comment += ( + '\nThis list was truncated, check the [container logfile]' + '({}) for the complete list.\n'.format(os.environ['CI_JOB_URL'])) + else: + comment += warnings.rstrip() + '\n' + backticks + '\n' + comment += ( + '\nYou can generate these warnings with `maintainer/CI/fix_style.sh`. ' + 'This is the same command that I have executed to generate the log above.' + ) + assert TOKEN_ESPRESSO_CI in comment + + requests.post(URL, json={'body': comment}) diff --git a/maintainer/gh_post_style_patch.py b/maintainer/gh_post_style_patch.py index f9ff687062d..5734d79a216 100755 --- a/maintainer/gh_post_style_patch.py +++ b/maintainer/gh_post_style_patch.py @@ -29,11 +29,13 @@ URL = 'https://api.github.com/repos/espressomd/espresso/issues/' + \ PR + '/comments?access_token=' + os.environ['GITHUB_TOKEN'] SIZELIMIT = 10000 +TOKEN_ESPRESSO_CI = 'style.patch' # Delete all existing comments comments = requests.get(URL) for comment in comments.json(): - if comment['user']['login'] == 'espresso-ci' and 'style.patch' in comment['body']: + if comment['user']['login'] == 'espresso-ci' and \ + TOKEN_ESPRESSO_CI in comment['body']: requests.delete(comment['url'] + '?access_token=' + os.environ['GITHUB_TOKEN']) @@ -61,4 +63,5 @@ comment += 'Please note that there are often multiple ways to correctly format code. As I am just a robot, I sometimes fail to identify the most aesthetically pleasing way. So please look over my suggested changes and adapt them where the style does not make sense.' if patch: + assert TOKEN_ESPRESSO_CI in comment requests.post(URL, json={'body': comment}) diff --git a/requirements.txt b/requirements.txt index d9414340b91..68211167c0e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,3 +4,6 @@ MDAnalysis>=0.16 pint>=0.9 autopep8==1.3.4 pycodestyle==2.3.1 +pylint>=2.2.2 +astroid>=2.1.0 +isort>=4.3.4 diff --git a/samples/immersed_boundary/addBending.py b/samples/immersed_boundary/addBending.py index dd59d015b39..e6a0faa21b4 100644 --- a/samples/immersed_boundary/addBending.py +++ b/samples/immersed_boundary/addBending.py @@ -26,7 +26,7 @@ def AddBending(system, kb): numAngles = int(fp.readline()) print("Found {}".format(numAngles)) # actual add - for i in range(0, numAngles): + for _ in range(0, numAngles): line = str.split(fp.readline()) id1 = int(line[0]) id2 = int(line[1]) diff --git a/samples/immersed_boundary/sampleImmersedBoundary.py b/samples/immersed_boundary/sampleImmersedBoundary.py index 903c2b8d210..ab8631c897f 100644 --- a/samples/immersed_boundary/sampleImmersedBoundary.py +++ b/samples/immersed_boundary/sampleImmersedBoundary.py @@ -26,7 +26,6 @@ espressomd.assert_features(required_features) from espressomd import lb, shapes, lbboundaries -import numpy as np from espressomd.virtual_sites import VirtualSitesInertialessTracers import argparse diff --git a/samples/lj-demo.py b/samples/lj-demo.py index ca7c8b4bb80..9bcfc625681 100644 --- a/samples/lj-demo.py +++ b/samples/lj-demo.py @@ -503,7 +503,7 @@ def midi_thread(): if controls.midi_input is not None and controls.midi_input.poll(): events = controls.midi_input.read(1000) for event in events: - status, data1, data2, data3 = event[0] + status, data1, data2, _ = event[0] if status == controls.MIDI_NUM_TEMPERATURE: temperature = data2 * \ (controls.max_temp - controls.min_temp) / \ diff --git a/samples/load_checkpoint.py b/samples/load_checkpoint.py index 1118821d67d..c10bffaae43 100644 --- a/samples/load_checkpoint.py +++ b/samples/load_checkpoint.py @@ -23,6 +23,7 @@ * P3M parameters. * thermostat. """ +# pylint: disable=undefined-variable import espressomd required_features = ["P3M", "WCA"] diff --git a/samples/object_in_fluid/motivation.py b/samples/object_in_fluid/motivation.py index c2ba663794d..ada5ab344f4 100644 --- a/samples/object_in_fluid/motivation.py +++ b/samples/object_in_fluid/motivation.py @@ -29,7 +29,6 @@ from espressomd import lbboundaries from espressomd import shapes -import numpy as np import os import argparse import warnings diff --git a/src/core/PartCfg.hpp b/src/core/PartCfg.hpp index 89784a14418..766ca5503e5 100644 --- a/src/core/PartCfg.hpp +++ b/src/core/PartCfg.hpp @@ -48,17 +48,17 @@ class GetLocalParts { public: Range operator()() const { - if (local_particles == nullptr) { + if (local_particles.empty()) { auto begin = skip_it(nullptr, nullptr, SkipIfNullOrGhost()); return {make_indirect_iterator(begin), make_indirect_iterator(begin)}; } - auto begin = - skip_it(local_particles, local_particles + max_seen_particle + 1, - SkipIfNullOrGhost()); - auto end = - skip_it(local_particles + max_seen_particle + 1, - local_particles + max_seen_particle + 1, SkipIfNullOrGhost()); + auto begin = skip_it(local_particles.data(), + local_particles.data() + max_seen_particle + 1, + SkipIfNullOrGhost()); + auto end = skip_it(local_particles.data() + max_seen_particle + 1, + local_particles.data() + max_seen_particle + 1, + SkipIfNullOrGhost()); return {make_indirect_iterator(begin), make_indirect_iterator(end)}; } diff --git a/src/core/constraints/Constraints.hpp b/src/core/constraints/Constraints.hpp index 90f4ba163cb..a121db96d17 100644 --- a/src/core/constraints/Constraints.hpp +++ b/src/core/constraints/Constraints.hpp @@ -36,7 +36,7 @@ template class Constraints { using const_iterator = typename container_type::const_iterator; private: - void reset_foces() const { + void reset_forces() const { for (auto const &c : *this) { c->reset_force(); } @@ -69,7 +69,7 @@ template class Constraints { if (m_constraints.empty()) return; - reset_foces(); + reset_forces(); for (auto &p : particles) { auto const pos = folded_position(p.r.p, box_geo); diff --git a/src/core/electrostatics_magnetostatics/fft.cpp b/src/core/electrostatics_magnetostatics/fft.cpp index 22331ac935f..95eb36cb14f 100644 --- a/src/core/electrostatics_magnetostatics/fft.cpp +++ b/src/core/electrostatics_magnetostatics/fft.cpp @@ -371,18 +371,19 @@ void forw_grid_comm(fft_forw_plan plan, const double *in, double *out, fft_data_struct &fft, const boost::mpi::communicator &comm) { for (int i = 0; i < plan.group.size(); i++) { - plan.pack_function(in, fft.send_buf, &(plan.send_block[6 * i]), + plan.pack_function(in, fft.send_buf.data(), &(plan.send_block[6 * i]), &(plan.send_block[6 * i + 3]), plan.old_mesh, plan.element); if (plan.group[i] != comm.rank()) { - MPI_Sendrecv(fft.send_buf, plan.send_size[i], MPI_DOUBLE, plan.group[i], - REQ_FFT_FORW, fft.recv_buf, plan.recv_size[i], MPI_DOUBLE, - plan.group[i], REQ_FFT_FORW, comm, MPI_STATUS_IGNORE); + MPI_Sendrecv(fft.send_buf.data(), plan.send_size[i], MPI_DOUBLE, + plan.group[i], REQ_FFT_FORW, fft.recv_buf.data(), + plan.recv_size[i], MPI_DOUBLE, plan.group[i], REQ_FFT_FORW, + comm, MPI_STATUS_IGNORE); } else { /* Self communication... */ std::swap(fft.send_buf, fft.recv_buf); } - fft_unpack_block(fft.recv_buf, out, &(plan.recv_block[6 * i]), + fft_unpack_block(fft.recv_buf.data(), out, &(plan.recv_block[6 * i]), &(plan.recv_block[6 * i + 3]), plan.new_mesh, plan.element); } @@ -404,19 +405,19 @@ void back_grid_comm(fft_forw_plan plan_f, fft_back_plan plan_b, versa. Attention then also new_mesh and old_mesh are exchanged */ for (int i = 0; i < plan_f.group.size(); i++) { - plan_b.pack_function(in, fft.send_buf, &(plan_f.recv_block[6 * i]), + plan_b.pack_function(in, fft.send_buf.data(), &(plan_f.recv_block[6 * i]), &(plan_f.recv_block[6 * i + 3]), plan_f.new_mesh, plan_f.element); if (plan_f.group[i] != comm.rank()) { /* send first, receive second */ - MPI_Sendrecv(fft.send_buf, plan_f.recv_size[i], MPI_DOUBLE, - plan_f.group[i], REQ_FFT_BACK, fft.recv_buf, + MPI_Sendrecv(fft.send_buf.data(), plan_f.recv_size[i], MPI_DOUBLE, + plan_f.group[i], REQ_FFT_BACK, fft.recv_buf.data(), plan_f.send_size[i], MPI_DOUBLE, plan_f.group[i], REQ_FFT_BACK, comm, MPI_STATUS_IGNORE); } else { /* Self communication... */ std::swap(fft.send_buf, fft.recv_buf); } - fft_unpack_block(fft.recv_buf, out, &(plan_f.send_block[6 * i]), + fft_unpack_block(fft.recv_buf.data(), out, &(plan_f.send_block[6 * i]), &(plan_f.send_block[6 * i + 3]), plan_f.old_mesh, plan_f.element); } @@ -553,10 +554,8 @@ int fft_init(double **data, int const *ca_mesh_dim, int const *ca_mesh_margin, n_id[i - 1], n_id[i], n_pos[i], my_pos[i], comm); if (not group) { /* try permutation */ - j = n_grid[i][(fft.plan[i].row_dir + 1) % 3]; - n_grid[i][(fft.plan[i].row_dir + 1) % 3] = - n_grid[i][(fft.plan[i].row_dir + 2) % 3]; - n_grid[i][(fft.plan[i].row_dir + 2) % 3] = j; + std::swap(n_grid[i][(fft.plan[i].row_dir + 1) % 3], + n_grid[i][(fft.plan[i].row_dir + 2) % 3]); group = find_comm_groups( {n_grid[i - 1][0], n_grid[i - 1][1], n_grid[i - 1][2]}, @@ -570,14 +569,10 @@ int fft_init(double **data, int const *ca_mesh_dim, int const *ca_mesh_margin, fft.plan[i].group = *group; - fft.plan[i].send_block = Utils::realloc( - fft.plan[i].send_block, 6 * fft.plan[i].group.size() * sizeof(int)); - fft.plan[i].send_size = Utils::realloc( - fft.plan[i].send_size, 1 * fft.plan[i].group.size() * sizeof(int)); - fft.plan[i].recv_block = Utils::realloc( - fft.plan[i].recv_block, 6 * fft.plan[i].group.size() * sizeof(int)); - fft.plan[i].recv_size = Utils::realloc( - fft.plan[i].recv_size, 1 * fft.plan[i].group.size() * sizeof(int)); + fft.plan[i].send_block.resize(6 * fft.plan[i].group.size()); + fft.plan[i].send_size.resize(fft.plan[i].group.size()); + fft.plan[i].recv_block.resize(6 * fft.plan[i].group.size()); + fft.plan[i].recv_size.resize(fft.plan[i].group.size()); fft.plan[i].new_size = calc_local_mesh(my_pos[i], n_grid[i], global_mesh_dim, global_mesh_off, @@ -652,10 +647,8 @@ int fft_init(double **data, int const *ca_mesh_dim, int const *ca_mesh_margin, } /* Factor 2 for complex numbers */ - fft.send_buf = - Utils::realloc(fft.send_buf, fft.max_comm_size * sizeof(double)); - fft.recv_buf = - Utils::realloc(fft.recv_buf, fft.max_comm_size * sizeof(double)); + fft.send_buf.resize(fft.max_comm_size); + fft.recv_buf.resize(fft.max_comm_size); if (*data) fftw_free(*data); (*data) = (double *)fftw_malloc(fft.max_mesh_size * sizeof(double)); @@ -704,7 +697,6 @@ int fft_init(double **data, int const *ca_mesh_dim, int const *ca_mesh_margin, } fft.init_tag = true; - /* free(data); */ for (i = 0; i < 4; i++) { free(n_id[i]); free(n_pos[i]); @@ -745,7 +737,6 @@ void fft_perform_forw(double *data, fft_data_struct &fft, void fft_perform_back(double *data, bool check_complex, fft_data_struct &fft, const boost::mpi::communicator &comm) { - int i; auto *c_data = (fftw_complex *)data; auto *c_data_buf = (fftw_complex *)fft.data_buf; @@ -767,7 +758,7 @@ void fft_perform_back(double *data, bool check_complex, fft_data_struct &fft, /* perform FFT (in is data) */ fftw_execute_dft(fft.back[1].our_fftw_plan, c_data, c_data); /* throw away the (hopefully) empty complex component (in is data)*/ - for (i = 0; i < fft.plan[1].new_size; i++) { + for (int i = 0; i < fft.plan[1].new_size; i++) { fft.data_buf[i] = data[2 * i]; /* real value */ // Vincent: if (check_complex && (data[2 * i + 1] > 1e-5)) { diff --git a/src/core/electrostatics_magnetostatics/fft.hpp b/src/core/electrostatics_magnetostatics/fft.hpp index 9cc59c39746..7d28b2ce7da 100644 --- a/src/core/electrostatics_magnetostatics/fft.hpp +++ b/src/core/electrostatics_magnetostatics/fft.hpp @@ -87,13 +87,13 @@ struct fft_forw_plan { void (*pack_function)(double const *const, double *const, int const *, int const *, int const *, int); /** Send block specification. 6 integers for each node: start[3], size[3]. */ - int *send_block = nullptr; + std::vector send_block; /** Send block communication sizes. */ - int *send_size = nullptr; + std::vector send_size; /** Recv block specification. 6 integers for each node: start[3], size[3]. */ - int *recv_block = nullptr; + std::vector recv_block; /** Recv block communication sizes. */ - int *recv_size = nullptr; + std::vector recv_size; /** size of send block elements. */ int element; }; @@ -133,9 +133,9 @@ struct fft_data_struct { int max_mesh_size = 0; /** send buffer. */ - double *send_buf = nullptr; + std::vector send_buf; /** receive buffer. */ - double *recv_buf = nullptr; + std::vector recv_buf; /** Buffer for receive data. */ double *data_buf = nullptr; }; diff --git a/src/core/electrostatics_magnetostatics/p3m-dipolar.cpp b/src/core/electrostatics_magnetostatics/p3m-dipolar.cpp index 6516a0a0ff5..ec8947771a1 100644 --- a/src/core/electrostatics_magnetostatics/p3m-dipolar.cpp +++ b/src/core/electrostatics_magnetostatics/p3m-dipolar.cpp @@ -286,31 +286,15 @@ dp3m_data_struct::dp3m_data_struct() { /* local_mesh is uninitialized */ /* sm is uninitialized */ rs_mesh = nullptr; - rs_mesh_dip[0] = nullptr; - rs_mesh_dip[1] = nullptr; - rs_mesh_dip[2] = nullptr; - ks_mesh = nullptr; sum_dip_part = 0; sum_mu2 = 0.0; - for (auto &i : int_caf) - i = nullptr; pos_shift = 0.0; - meshift = nullptr; - - d_op = nullptr; - g_force = nullptr; - g_energy = nullptr; ca_num = 0; - ca_frac = nullptr; - ca_fmp = nullptr; ks_pnum = 0; - send_grid = nullptr; - recv_grid = nullptr; - energy_correction = 0.0; } @@ -354,10 +338,8 @@ void dp3m_init() { dp3m_calc_send_mesh(); - dp3m.send_grid = - Utils::realloc(dp3m.send_grid, sizeof(double) * dp3m.sm.max); - dp3m.recv_grid = - Utils::realloc(dp3m.recv_grid, sizeof(double) * dp3m.sm.max); + dp3m.send_grid.resize(dp3m.sm.max); + dp3m.recv_grid.resize(dp3m.sm.max); /* fix box length dependent constants */ dp3m_scaleby_box_l(); @@ -372,11 +354,11 @@ void dp3m_init() { fft_init(&dp3m.rs_mesh, dp3m.local_mesh.dim, dp3m.local_mesh.margin, dp3m.params.mesh, dp3m.params.mesh_off, &dp3m.ks_pnum, dp3m.fft, node_grid, comm_cart); - dp3m.ks_mesh = Utils::realloc(dp3m.ks_mesh, ca_mesh_size * sizeof(double)); + dp3m.ks_mesh.resize(ca_mesh_size); - for (n = 0; n < 3; n++) - dp3m.rs_mesh_dip[n] = - Utils::realloc(dp3m.rs_mesh_dip[n], ca_mesh_size * sizeof(double)); + for (auto &val : dp3m.rs_mesh_dip) { + val.resize(ca_mesh_size); + } /* k-space part: */ @@ -391,13 +373,13 @@ void dp3m_init() { void dp3m_free_dipoles() { for (auto &i : dp3m.rs_mesh_dip) - free(i); - free(dp3m.ca_frac); - free(dp3m.ca_fmp); - free(dp3m.send_grid); - free(dp3m.recv_grid); + i.resize(0); + dp3m.ca_frac.resize(0); + dp3m.ca_fmp.resize(0); + dp3m.send_grid.resize(0); + dp3m.recv_grid.resize(0); free(dp3m.rs_mesh); - free(dp3m.ks_mesh); + dp3m.ks_mesh.resize(0); } double dp3m_average_dipolar_self_energy(double box_l, int mesh) { @@ -586,8 +568,7 @@ void dp3m_interpolate_dipole_assignment_function() { for (i = 0; i < dp3m.params.cao; i++) { /* allocate memory for interpolation array */ - dp3m.int_caf[i] = Utils::realloc( - dp3m.int_caf[i], sizeof(double) * (2 * dp3m.params.inter + 1)); + dp3m.int_caf[i].resize(2 * dp3m.params.inter + 1); /* loop over all interpolation points */ for (j = -dp3m.params.inter; j <= dp3m.params.inter; j++) @@ -641,7 +622,7 @@ void dp3m_assign_dipole(double const real_pos[3], double mu, dp3m_realloc_ca_fields(cp_cnt + 1); // do it here, since p3m_realloc_ca_fields may change the address of // dp3m.ca_frac - cur_ca_frac = dp3m.ca_frac + dp3m.params.cao3 * cp_cnt; + cur_ca_frac = dp3m.ca_frac.data() + dp3m.params.cao3 * cp_cnt; if (dp3m.params.inter == 0) { for (d = 0; d < 3; d++) { @@ -836,12 +817,12 @@ double dp3m_calc_kspace_forces(bool force_flag, bool energy_flag, if (dp3m.sum_mu2 > 0) { /* Gather information for FFT grid inside the nodes domain (inner local * mesh) and Perform forward 3D FFT (Charge Assignment Mesh). */ - dp3m_gather_fft_grid(dp3m.rs_mesh_dip[0]); - dp3m_gather_fft_grid(dp3m.rs_mesh_dip[1]); - dp3m_gather_fft_grid(dp3m.rs_mesh_dip[2]); - fft_perform_forw(dp3m.rs_mesh_dip[0], dp3m.fft, comm_cart); - fft_perform_forw(dp3m.rs_mesh_dip[1], dp3m.fft, comm_cart); - fft_perform_forw(dp3m.rs_mesh_dip[2], dp3m.fft, comm_cart); + dp3m_gather_fft_grid(dp3m.rs_mesh_dip[0].data()); + dp3m_gather_fft_grid(dp3m.rs_mesh_dip[1].data()); + dp3m_gather_fft_grid(dp3m.rs_mesh_dip[2].data()); + fft_perform_forw(dp3m.rs_mesh_dip[0].data(), dp3m.fft, comm_cart); + fft_perform_forw(dp3m.rs_mesh_dip[1].data(), dp3m.fft, comm_cart); + fft_perform_forw(dp3m.rs_mesh_dip[2].data(), dp3m.fft, comm_cart); // Note: after these calls, the grids are in the order yzx and not xyz // anymore!!! } @@ -1044,13 +1025,16 @@ double dp3m_calc_kspace_forces(bool force_flag, bool energy_flag, } } /* Back FFT force component mesh */ - fft_perform_back(dp3m.rs_mesh_dip[0], false, dp3m.fft, comm_cart); - fft_perform_back(dp3m.rs_mesh_dip[1], false, dp3m.fft, comm_cart); - fft_perform_back(dp3m.rs_mesh_dip[2], false, dp3m.fft, comm_cart); + fft_perform_back(dp3m.rs_mesh_dip[0].data(), false, dp3m.fft, + comm_cart); + fft_perform_back(dp3m.rs_mesh_dip[1].data(), false, dp3m.fft, + comm_cart); + fft_perform_back(dp3m.rs_mesh_dip[2].data(), false, dp3m.fft, + comm_cart); /* redistribute force component mesh */ - dp3m_spread_force_grid(dp3m.rs_mesh_dip[0]); - dp3m_spread_force_grid(dp3m.rs_mesh_dip[1]); - dp3m_spread_force_grid(dp3m.rs_mesh_dip[2]); + dp3m_spread_force_grid(dp3m.rs_mesh_dip[0].data()); + dp3m_spread_force_grid(dp3m.rs_mesh_dip[1].data()); + dp3m_spread_force_grid(dp3m.rs_mesh_dip[2].data()); /* Assign force component from mesh to particle */ dp3m_assign_forces_dip( dipole_prefac * pow(2 * Utils::pi() / box_geo.length()[0], 2), d_rs, @@ -1150,7 +1134,6 @@ double calc_surface_term(bool force_flag, bool energy_flag, void dp3m_gather_fft_grid(double *themesh) { int s_dir, r_dir, evenodd; MPI_Status status; - double *tmp_ptr; auto const node_neighbors = calc_node_neighbors(comm_cart); auto const node_pos = calc_node_pos(comm_cart); @@ -1163,7 +1146,7 @@ void dp3m_gather_fft_grid(double *themesh) { r_dir = s_dir - 1; /* pack send block */ if (dp3m.sm.s_size[s_dir] > 0) - fft_pack_block(themesh, dp3m.send_grid, dp3m.sm.s_ld[s_dir], + fft_pack_block(themesh, dp3m.send_grid.data(), dp3m.sm.s_ld[s_dir], dp3m.sm.s_dim[s_dir], dp3m.local_mesh.dim, 1); /* communication */ @@ -1171,23 +1154,21 @@ void dp3m_gather_fft_grid(double *themesh) { for (evenodd = 0; evenodd < 2; evenodd++) { if ((node_pos[s_dir / 2] + evenodd) % 2 == 0) { if (dp3m.sm.s_size[s_dir] > 0) - MPI_Send(dp3m.send_grid, dp3m.sm.s_size[s_dir], MPI_DOUBLE, + MPI_Send(dp3m.send_grid.data(), dp3m.sm.s_size[s_dir], MPI_DOUBLE, node_neighbors[s_dir], REQ_P3M_GATHER_D, comm_cart); } else { if (dp3m.sm.r_size[r_dir] > 0) - MPI_Recv(dp3m.recv_grid, dp3m.sm.r_size[r_dir], MPI_DOUBLE, + MPI_Recv(dp3m.recv_grid.data(), dp3m.sm.r_size[r_dir], MPI_DOUBLE, node_neighbors[r_dir], REQ_P3M_GATHER_D, comm_cart, &status); } } } else { - tmp_ptr = dp3m.recv_grid; - dp3m.recv_grid = dp3m.send_grid; - dp3m.send_grid = tmp_ptr; + std::swap(dp3m.send_grid, dp3m.recv_grid); } /* add recv block */ if (dp3m.sm.r_size[r_dir] > 0) { - p3m_add_block(dp3m.recv_grid, themesh, dp3m.sm.r_ld[r_dir], + p3m_add_block(dp3m.recv_grid.data(), themesh, dp3m.sm.r_ld[r_dir], dp3m.sm.r_dim[r_dir], dp3m.local_mesh.dim); } } @@ -1198,7 +1179,6 @@ void dp3m_gather_fft_grid(double *themesh) { void dp3m_spread_force_grid(double *themesh) { int s_dir, r_dir, evenodd; MPI_Status status; - double *tmp_ptr; auto const node_neighbors = calc_node_neighbors(comm_cart); auto const node_pos = calc_node_pos(comm_cart); @@ -1211,30 +1191,28 @@ void dp3m_spread_force_grid(double *themesh) { r_dir = s_dir - 1; /* pack send block */ if (dp3m.sm.s_size[s_dir] > 0) - fft_pack_block(themesh, dp3m.send_grid, dp3m.sm.r_ld[r_dir], + fft_pack_block(themesh, dp3m.send_grid.data(), dp3m.sm.r_ld[r_dir], dp3m.sm.r_dim[r_dir], dp3m.local_mesh.dim, 1); /* communication */ if (node_neighbors[r_dir] != this_node) { for (evenodd = 0; evenodd < 2; evenodd++) { if ((node_pos[r_dir / 2] + evenodd) % 2 == 0) { if (dp3m.sm.r_size[r_dir] > 0) - MPI_Send(dp3m.send_grid, dp3m.sm.r_size[r_dir], MPI_DOUBLE, + MPI_Send(dp3m.send_grid.data(), dp3m.sm.r_size[r_dir], MPI_DOUBLE, node_neighbors[r_dir], REQ_P3M_SPREAD_D, comm_cart); } else { if (dp3m.sm.s_size[s_dir] > 0) - MPI_Recv(dp3m.recv_grid, dp3m.sm.s_size[s_dir], MPI_DOUBLE, + MPI_Recv(dp3m.recv_grid.data(), dp3m.sm.s_size[s_dir], MPI_DOUBLE, node_neighbors[s_dir], REQ_P3M_SPREAD_D, comm_cart, &status); } } } else { - tmp_ptr = dp3m.recv_grid; - dp3m.recv_grid = dp3m.send_grid; - dp3m.send_grid = tmp_ptr; + std::swap(dp3m.send_grid, dp3m.recv_grid); } /* un pack recv block */ if (dp3m.sm.s_size[s_dir] > 0) { - fft_unpack_block(dp3m.recv_grid, themesh, dp3m.sm.s_ld[s_dir], + fft_unpack_block(dp3m.recv_grid.data(), themesh, dp3m.sm.s_ld[s_dir], dp3m.sm.s_dim[s_dir], dp3m.local_mesh.dim, 1); } } @@ -1250,9 +1228,8 @@ void dp3m_realloc_ca_fields(int newsize) { newsize = CA_INCREMENT; dp3m.ca_num = newsize; - dp3m.ca_frac = Utils::realloc(dp3m.ca_frac, dp3m.params.cao3 * dp3m.ca_num * - sizeof(double)); - dp3m.ca_fmp = Utils::realloc(dp3m.ca_fmp, dp3m.ca_num * sizeof(int)); + dp3m.ca_frac.resize(dp3m.params.cao3 * dp3m.ca_num); + dp3m.ca_fmp.resize(dp3m.ca_num); } /*****************************************************************************/ @@ -1261,8 +1238,7 @@ void dp3m_calc_meshift() { int i; double dmesh; dmesh = (double)dp3m.params.mesh[0]; - dp3m.meshift = - Utils::realloc(dp3m.meshift, dp3m.params.mesh[0] * sizeof(double)); + dp3m.meshift.resize(dp3m.params.mesh[0]); for (i = 0; i < dp3m.params.mesh[0]; i++) dp3m.meshift[i] = i - std::round(i / dmesh) * dmesh; } @@ -1274,7 +1250,7 @@ void dp3m_calc_differential_operator() { double dmesh; dmesh = (double)dp3m.params.mesh[0]; - dp3m.d_op = Utils::realloc(dp3m.d_op, dp3m.params.mesh[0] * sizeof(double)); + dp3m.d_op.resize(dp3m.params.mesh[0]); for (i = 0; i < dp3m.params.mesh[0]; i++) dp3m.d_op[i] = (double)i - std::round((double)i / dmesh) * dmesh; @@ -1297,7 +1273,7 @@ void dp3m_calc_influence_function_force() { size *= dp3m.fft.plan[3].new_mesh[i]; end[i] = dp3m.fft.plan[3].start[i] + dp3m.fft.plan[3].new_mesh[i]; } - dp3m.g_force = Utils::realloc(dp3m.g_force, size * sizeof(double)); + dp3m.g_force.resize(size); fak1 = dp3m.params.mesh[0] * dp3m.params.mesh[0] * dp3m.params.mesh[0] * 2.0 / (box_geo.length()[0] * box_geo.length()[0]); @@ -1385,7 +1361,7 @@ void dp3m_calc_influence_function_energy() { size *= dp3m.fft.plan[3].new_mesh[i]; end[i] = dp3m.fft.plan[3].start[i] + dp3m.fft.plan[3].new_mesh[i]; } - dp3m.g_energy = Utils::realloc(dp3m.g_energy, size * sizeof(double)); + dp3m.g_energy.resize(size); fak1 = dp3m.params.mesh[0] * dp3m.params.mesh[0] * dp3m.params.mesh[0] * 2.0 / (box_geo.length()[0] * box_geo.length()[0]); diff --git a/src/core/electrostatics_magnetostatics/p3m-dipolar.hpp b/src/core/electrostatics_magnetostatics/p3m-dipolar.hpp index 4b0243c9c4b..360ee91739a 100644 --- a/src/core/electrostatics_magnetostatics/p3m-dipolar.hpp +++ b/src/core/electrostatics_magnetostatics/p3m-dipolar.hpp @@ -58,9 +58,9 @@ struct dp3m_data_struct { /** real space mesh (local) for CA/FFT.*/ double *rs_mesh; /** real space mesh (local) for CA/FFT of the dipolar field.*/ - double *rs_mesh_dip[3]; + std::vector> rs_mesh_dip{3}; /** k-space mesh (local) for k-space calculation and FFT.*/ - double *ks_mesh; + std::vector ks_mesh; /** number of dipolar particles (only on master node). */ int sum_dip_part; @@ -68,28 +68,28 @@ struct dp3m_data_struct { double sum_mu2; /** interpolation of the charge assignment function. */ - double *int_caf[7]; + std::vector> int_caf{7}; /** position shift for calc. of first assignment mesh point. */ double pos_shift; /** help variable for calculation of aliasing sums */ - double *meshift; + std::vector meshift; /** Spatial differential operator in k-space. We use an i*k differentiation. */ - double *d_op; + std::vector d_op; /** Force optimised influence function (k-space) */ - double *g_force; + std::vector g_force; /** Energy optimised influence function (k-space) */ - double *g_energy; + std::vector g_energy; /** number of charged particles on the node. */ int ca_num; /** Charge fractions for mesh assignment. */ - double *ca_frac; + std::vector ca_frac; /** index of first mesh point for charge assignment. */ - int *ca_fmp; + std::vector ca_fmp; /** number of permutations in k_space */ int ks_pnum; @@ -97,9 +97,9 @@ struct dp3m_data_struct { p3m_send_mesh sm; /** Field to store grid points to send. */ - double *send_grid; + std::vector send_grid; /** Field to store grid points to recv */ - double *recv_grid; + std::vector recv_grid; /* Stores the value of the energy correction due to MS effects */ double energy_correction; diff --git a/src/core/io/mpiio/mpiio.cpp b/src/core/io/mpiio/mpiio.cpp index a22ff999b03..191f0d2c745 100644 --- a/src/core/io/mpiio/mpiio.cpp +++ b/src/core/io/mpiio/mpiio.cpp @@ -378,10 +378,8 @@ void mpi_mpiio_common_read(const char *filename, unsigned fields) { read_prefs(fnam + ".pref", rank, size, nglobalpart, &pref, &nlocalpart); // Prepare ESPResSo data structures - local_particles = - Utils::realloc(local_particles, sizeof(Particle *) * nglobalpart); - for (int i = 0; i < nglobalpart; ++i) - local_particles[i] = nullptr; + local_particles.resize(nglobalpart); + std::fill(local_particles.begin(), local_particles.end(), nullptr); n_part = nglobalpart; max_seen_particle = nglobalpart; diff --git a/src/core/particle_data.cpp b/src/core/particle_data.cpp index c81dd185691..cd684f670b6 100644 --- a/src/core/particle_data.cpp +++ b/src/core/particle_data.cpp @@ -397,8 +397,7 @@ bool swimming_particles_exist = false; */ std::unordered_map particle_node; -int max_local_particles = 0; -Particle **local_particles = nullptr; +std::vector local_particles; /************************************************ * local functions @@ -502,15 +501,11 @@ void clear_particle_node() { particle_node.clear(); } void realloc_local_particles(int part) { constexpr auto INCREMENT = 8; - if (part >= max_local_particles) { - /* round up part + 1 in granularity INCREMENT */ - max_local_particles = INCREMENT * ((part + INCREMENT) / INCREMENT); - local_particles = Utils::realloc(local_particles, - sizeof(Particle *) * max_local_particles); - - /* Set new memory to 0 */ - for (int i = (max_seen_particle + 1); i < max_local_particles; i++) - local_particles[i] = nullptr; + if (part >= local_particles.size()) { + /* increase vector size by round up part + 1 in granularity INCREMENT and + * set new memory to nullptr */ + local_particles.resize(INCREMENT * ((part + INCREMENT) / INCREMENT), + nullptr); } } @@ -1118,7 +1113,7 @@ void local_remove_all_particles() { int c; n_part = 0; max_seen_particle = -1; - std::fill(local_particles, local_particles + max_local_particles, nullptr); + std::fill(local_particles.begin(), local_particles.end(), nullptr); for (c = 0; c < local_cells.n; c++) { Particle *p; diff --git a/src/core/particle_data.hpp b/src/core/particle_data.hpp index 111b224c4e9..3cb85f60aab 100644 --- a/src/core/particle_data.hpp +++ b/src/core/particle_data.hpp @@ -87,8 +87,7 @@ extern bool swimming_particles_exist; /** id->particle mapping on all nodes. This is used to find partners of bonded interactions. */ -extern Particle **local_particles; -extern int max_local_particles; +extern std::vector local_particles; /************************************************ * Functions diff --git a/src/core/statistics.cpp b/src/core/statistics.cpp index 111d9504e39..e022a364aa6 100644 --- a/src/core/statistics.cpp +++ b/src/core/statistics.cpp @@ -354,9 +354,7 @@ void calc_rdf_av(PartCfg &partCfg, int const *p1_types, int n_p1, bool mixed_flag = false; double inv_bin_width = 0.0, bin_width = 0.0; double volume, bin_volume, r_in, r_out; - double *rdf_tmp; - - rdf_tmp = (double *)Utils::malloc(r_bins * sizeof(double)); + std::vector rdf_tmp(r_bins); if (n_p1 == n_p2) { for (int i = 0; i < n_p1; i++) @@ -426,7 +424,6 @@ void calc_rdf_av(PartCfg &partCfg, int const *p1_types, int n_p1, for (int i = 0; i < r_bins; i++) { rdf[i] /= (cnt_conf - 1); } - free(rdf_tmp); } std::vector calc_structurefactor(PartCfg &partCfg, int const *p_types, diff --git a/src/python/espressomd/MDA_ESP/__init__.py b/src/python/espressomd/MDA_ESP/__init__.py index 9cbad2cfec5..e23a70d2155 100644 --- a/src/python/espressomd/MDA_ESP/__init__.py +++ b/src/python/espressomd/MDA_ESP/__init__.py @@ -58,6 +58,7 @@ from MDAnalysis.lib import util from MDAnalysis.coordinates.core import triclinic_box +from MDAnalysis.coordinates.core import triclinic_vectors from MDAnalysis.lib.util import NamedStream from MDAnalysis.topology.base import TopologyReaderBase from MDAnalysis.coordinates import base @@ -125,7 +126,7 @@ class ESPParser(TopologyReaderBase): """ format = 'ESP' - def __init__(self, filename, **kwargs): + def __init__(self, filename, **kwargs): # pylint: disable=unused-argument self.kwargs = kwargs def parse(self): @@ -191,7 +192,7 @@ def dimensions(self): @dimensions.setter def dimensions(self, box): - x, y, z = triclinic_vectors(box) + x, y, _ = triclinic_vectors(box) np.put(self._unitcell, self._ts_order_x, x) np.put(self._unitcell, self._ts_order_y, y) diff --git a/src/python/espressomd/checkpointing.py b/src/python/espressomd/checkpointing.py index 8b41a8ac674..513d4bc3af1 100644 --- a/src/python/espressomd/checkpointing.py +++ b/src/python/espressomd/checkpointing.py @@ -235,7 +235,7 @@ def load(self, checkpoint_index=None): self.calling_module, key, checkpoint_data[key]) self.checkpoint_objects.append(key) - def __signal_handler(self, signum, frame): + def __signal_handler(self, signum, frame): # pylint: disable=unused-argument """ Will be called when a registered signal was sent. diff --git a/src/python/espressomd/highlander.py b/src/python/espressomd/highlander.py index 87132d670a3..f27d110062c 100644 --- a/src/python/espressomd/highlander.py +++ b/src/python/espressomd/highlander.py @@ -32,7 +32,7 @@ def __str__(self): def highlander(klass): klass.highlander_created = False - def cls_init(self, *args, **kwargs): + def cls_init(self, *args, **kwargs): # pylint: disable=unused-argument "__init__ method by the highlander decorator." if self.__class__.highlander_created: raise ThereCanOnlyBeOne(self.__class__) diff --git a/src/python/object_in_fluid/oif_utils.py b/src/python/object_in_fluid/oif_utils.py index e29b4701512..19539cd5474 100644 --- a/src/python/object_in_fluid/oif_utils.py +++ b/src/python/object_in_fluid/oif_utils.py @@ -565,9 +565,8 @@ def output_vtk_lines(lines, out_file): return 0 -def output_vtk_pore( - axis, length, outer_rad_left, outer_rad_right, pos, rad_left, rad_right, - smoothing_radius, m, out_file): +def output_vtk_pore(axis, length, outer_rad_left, outer_rad_right, # pylint: disable=unused-argument + pos, rad_left, rad_right, smoothing_radius, m, out_file): """ Outputs the VTK files for visualisation of a pore in e.g. Paraview. @@ -601,9 +600,8 @@ def output_vtk_pore( # should implement rotation # m is sufficient to be 10 - if ".vtk" not in out_file: - print( - "output_vtk_pore warning: A file with vtk format will be written without .vtk extension.") + if not out_file.endswith(".vtk"): + print("output_vtk_pore warning: A file with vtk format will be written without .vtk extension.") # n must be even therefore: n = 2 * m diff --git a/testsuite/python/drude.py b/testsuite/python/drude.py index 39bb2f70cd2..96adbc7e8ad 100644 --- a/testsuite/python/drude.py +++ b/testsuite/python/drude.py @@ -244,8 +244,7 @@ def measure_pol(Es, dim): E[dim] = Es setElectricField(E) - mux_pf6, mux_c1, mux_c2, mux_c3, mux_bmim = measure_dipole_moments( - ) + mux_pf6, _, _, _, mux_bmim = measure_dipole_moments() return calc_pol(mu0_pf6[dim], mux_pf6[dim], Es), calc_pol( mu0_bmim[dim], mux_bmim[dim], Es) diff --git a/testsuite/python/ek_common.py b/testsuite/python/ek_common.py index 9107a3fc019..d13765b46f3 100644 --- a/testsuite/python/ek_common.py +++ b/testsuite/python/ek_common.py @@ -64,9 +64,6 @@ def pressure_tensor_offdiagonal(x, xi, bjerrum_length, force): def hydrostatic_pressure( ek, - x, - xi, - bjerrum_length, tensor_entry, box_x, box_y, diff --git a/testsuite/python/ek_eof_one_species_base.py b/testsuite/python/ek_eof_one_species_base.py index 0d58e852400..ba8f7d7382e 100644 --- a/testsuite/python/ek_eof_one_species_base.py +++ b/testsuite/python/ek_eof_one_species_base.py @@ -208,9 +208,6 @@ def run_test(self, params): measured_pressure_xx = ek[index].pressure[(0, 0)] calculated_pressure_xx = ek_common.hydrostatic_pressure( ek, - position, - self.xi, - params_base['bjerrum_length'], (0, 0), system.box_l[params['periodic_dirs'][0]], system.box_l[params['periodic_dirs'][1]], @@ -219,9 +216,6 @@ def run_test(self, params): measured_pressure_yy = ek[index].pressure[(1, 1)] calculated_pressure_yy = ek_common.hydrostatic_pressure( ek, - position, - self.xi, - params_base['bjerrum_length'], (1, 1), system.box_l[params['periodic_dirs'][0]], system.box_l[params['periodic_dirs'][1]], @@ -230,9 +224,6 @@ def run_test(self, params): measured_pressure_zz = ek[index].pressure[(2, 2)] calculated_pressure_zz = ek_common.hydrostatic_pressure( ek, - position, - self.xi, - params_base['bjerrum_length'], (2, 2), system.box_l[params['periodic_dirs'][0]], system.box_l[params['periodic_dirs'][1]], diff --git a/testsuite/python/engine_lb.py b/testsuite/python/engine_lb.py index fbdb83a26ff..51d6ca4bb2d 100644 --- a/testsuite/python/engine_lb.py +++ b/testsuite/python/engine_lb.py @@ -17,7 +17,7 @@ import unittest as ut import unittest_decorators as utx import numpy as np -from espressomd import System, lb, shapes, lbboundaries +from espressomd import System, lb class SwimmerTest(): diff --git a/testsuite/python/interactions_bonded.py b/testsuite/python/interactions_bonded.py index 1a2610ae19c..71434eb13be 100644 --- a/testsuite/python/interactions_bonded.py +++ b/testsuite/python/interactions_bonded.py @@ -57,9 +57,9 @@ def test_harmonic(self): k=hb_k, r_0=hb_r_0, r_cut=hb_r_cut) self.run_test(hb, lambda r: tests_common.harmonic_force( - scalar_r=r, k=hb_k, r_0=hb_r_0, r_cut=hb_r_cut), + scalar_r=r, k=hb_k, r_0=hb_r_0), lambda r: tests_common.harmonic_potential( - scalar_r=r, k=hb_k, r_0=hb_r_0, r_cut=hb_r_cut), + scalar_r=r, k=hb_k, r_0=hb_r_0), 0.01, hb_r_cut, True) # Test Fene Bond diff --git a/testsuite/python/lb_boundary_volume_force.py b/testsuite/python/lb_boundary_volume_force.py index 1d154172dea..ab0b3fb3235 100644 --- a/testsuite/python/lb_boundary_volume_force.py +++ b/testsuite/python/lb_boundary_volume_force.py @@ -53,7 +53,7 @@ class LBBoundaryForceCommon: def test(self): """ Integrate the LB fluid until steady state is reached within a certain - accuracy. Then compare the foce balance between force exerted on fluid + accuracy. Then compare the force balance between force exerted on fluid and forces acting on the boundaries. """ @@ -79,7 +79,6 @@ def test(self): diff = abs(new_val - old_val) old_val = new_val - surface_area = self.system.box_l[1] * self.system.box_l[2] expected_force = fluid_nodes * AGRID**3 * \ np.copy(self.lbf.ext_force_density) measured_force = np.array(wall1.get_force()) + \ diff --git a/testsuite/python/lb_buoyancy_force.py b/testsuite/python/lb_buoyancy_force.py index 4c4945223ef..d65c4d768a2 100644 --- a/testsuite/python/lb_buoyancy_force.py +++ b/testsuite/python/lb_buoyancy_force.py @@ -16,7 +16,7 @@ # along with this program. If not, see . import espressomd -from espressomd import lb, lbboundaries, shapes, has_features +from espressomd import lbboundaries, shapes import unittest as ut import numpy as np import unittest_decorators as utx diff --git a/testsuite/python/lb_momentum_conservation.py b/testsuite/python/lb_momentum_conservation.py index 1dd7c85bf6d..906c0f99ae1 100644 --- a/testsuite/python/lb_momentum_conservation.py +++ b/testsuite/python/lb_momentum_conservation.py @@ -16,10 +16,8 @@ # along with this program. If not, see . import espressomd -from espressomd import lb, lbboundaries, shapes, has_features import unittest as ut import numpy as np -import sys # Define the LB Parameters TIME_STEP = 0.1 @@ -65,7 +63,7 @@ def test(self): v_final = np.copy(p.v) momentum = self.system.analysis.linear_momentum() - for i in range(10): + for _ in range(10): self.system.integrator.run(50) # check that momentum stays constant np.testing.assert_allclose( diff --git a/testsuite/python/observable_chain.py b/testsuite/python/observable_chain.py index b48d73c430e..217da4420b1 100644 --- a/testsuite/python/observable_chain.py +++ b/testsuite/python/observable_chain.py @@ -139,7 +139,7 @@ def rotate_vector(v, k, phi): np.sin(phi) + k * np.dot(k, v) * (1.0 - np.cos(phi)) return vrot - def rotate_particle(p1, p2, p3, p4, phi): + def rotate_particle(p2, p3, p4, phi): """Rotates particle p4 around the axis formed by the bond between p2 and p3.""" k = p3 - p2 @@ -182,10 +182,10 @@ def place_particles(bl, offset): # place particles and keep list of unfolded positions pos = place_particles(bond_length, 3 * [offset]) # rotate the 1st particle - p[0].pos = pos[0] = rotate_particle(*pos[0:4, :][::-1], + p[0].pos = pos[0] = rotate_particle(*pos[1:4, :][::-1], phi=phi) # rotate the 5th particle - p[4].pos = pos[4] = rotate_particle(*pos[1:5, :], phi=phi) + p[4].pos = pos[4] = rotate_particle(*pos[2:5, :], phi=phi) # expected values dih1 = calculate_dihedral(*pos[0:4, :][::-1]) dih2 = calculate_dihedral(*pos[1:5, :]) diff --git a/testsuite/python/test_checkpoint.py b/testsuite/python/test_checkpoint.py index 66ec0f451b8..5baa6bfc004 100644 --- a/testsuite/python/test_checkpoint.py +++ b/testsuite/python/test_checkpoint.py @@ -15,6 +15,7 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +# pylint: disable=undefined-variable import unittest as ut import unittest_decorators as utx import numpy as np @@ -195,7 +196,7 @@ def test_integrator_SD(self): self.assertEqual(params['max_displacement'], 0.01) @ut.skipIf('INT.NVT' not in modes, 'NVT integrator not in modes') - def test_integrator_VV(self): + def test_integrator_NVT(self): integ = system.integrator.get_state() self.assertEqual(integ['_method'], 'NVT') diff --git a/testsuite/python/tests_common.py b/testsuite/python/tests_common.py index f04dca7c4ee..53b6fe5d8cb 100644 --- a/testsuite/python/tests_common.py +++ b/testsuite/python/tests_common.py @@ -283,11 +283,11 @@ def get_cylindrical_bin_volume( # Harmonic bond -def harmonic_potential(scalar_r, k, r_0, r_cut): +def harmonic_potential(scalar_r, k, r_0): return 0.5 * k * (scalar_r - r_0)**2 -def harmonic_force(scalar_r, k, r_0, r_cut): +def harmonic_force(scalar_r, k, r_0): return -k * (scalar_r - r_0) # FENE bond diff --git a/testsuite/python/writevtf.py b/testsuite/python/writevtf.py index c3af78754a9..61b3dac85f8 100644 --- a/testsuite/python/writevtf.py +++ b/testsuite/python/writevtf.py @@ -78,7 +78,6 @@ def test_bonds(self): if self.types_to_write == 'all': simulation_bonds = np.array([1, 2, 3]) # the two bonded particles elif 2 in self.types_to_write: - types = [2] simulation_bonds = np.array(2) # only this one is type 2 self.assertTrue(np.allclose( diff --git a/testsuite/scripts/tutorials/test_04-lattice_boltzmann_part3_solution.py b/testsuite/scripts/tutorials/test_04-lattice_boltzmann_part3_solution.py index 12e60d8acd7..81bcb0b7093 100644 --- a/testsuite/scripts/tutorials/test_04-lattice_boltzmann_part3_solution.py +++ b/testsuite/scripts/tutorials/test_04-lattice_boltzmann_part3_solution.py @@ -17,7 +17,6 @@ import unittest as ut import importlib_wrapper -import numpy as np tutorial, skipIfMissingFeatures = importlib_wrapper.configure_and_import( diff --git a/testsuite/scripts/tutorials/test_04-lattice_boltzmann_part4.py b/testsuite/scripts/tutorials/test_04-lattice_boltzmann_part4.py index fa7a54de2c6..aaccf3b6dc2 100644 --- a/testsuite/scripts/tutorials/test_04-lattice_boltzmann_part4.py +++ b/testsuite/scripts/tutorials/test_04-lattice_boltzmann_part4.py @@ -17,7 +17,6 @@ import unittest as ut import importlib_wrapper -import numpy as np tutorial, skipIfMissingFeatures = importlib_wrapper.configure_and_import( diff --git a/testsuite/scripts/tutorials/test_12-constant_pH.py b/testsuite/scripts/tutorials/test_12-constant_pH.py index 55bc710a457..57a1beff84c 100644 --- a/testsuite/scripts/tutorials/test_12-constant_pH.py +++ b/testsuite/scripts/tutorials/test_12-constant_pH.py @@ -20,7 +20,7 @@ import numpy as np try: - import pint + import pint # pylint: disable=unused-import except ImportError: tutorial = importlib_wrapper.MagicMock() skipIfMissingFeatures = ut.skip(