Git Product home page Git Product logo

amepproject / amep Goto Github PK

View Code? Open in Web Editor NEW
10.0 0.0 2.0 48.3 MB

The Active Matter Evaluation Package (AMEP) - a Python library for the analysis of particle-based and continuum simulation data of soft and active matter systems

Home Page: https://amepproject.de/

License: GNU General Public License v3.0

Python 100.00%
active-matter analysis brownian-dynamics brownian-dynamics-simulation coarse-graining computational-physics data-analysis molecular-dynamics molecular-dynamics-simulation physics python soft-matter trajectory-analysis scientific-computing scientific-visualization visualization

amep's Introduction

License: GPL v3 GitHub Discussions Python Version from PEP 621 TOML Static Badge Pepy Total Downlods Conda Downloads GitHub Actions Workflow Status Static Badge

amep logo

The AMEP (Active Matter Evaluation Package) Python library is a powerful tool for analyzing data from molecular-dynamics (MD), Brownian-dynamics (BD), and continuum simulations. It comprises various methods to analyze structural and dynamical properties of condensed matter systems in general and active matter systems in particular. AMEP is exclusively built on Python, and therefore, it is easy to modify and allows to easily add user-defined functions. AMEP provides an efficient data format for saving both simulation data and analysis results based on the HDF5 file format. To be fast and usable on modern HPC (High Performance Computing) hardware, the methods are optimized to run also in parallel.

Description

The AMEP Python library provides a unified framework for handling both particle-based and continuum simulation data. It is made for the analysis of molecular-dynamics (MD), Brownian-dynamics (BD), and continuum simulation data of condensed matter systems and active matter systems in particular. AMEP provides a huge variety of analysis methods for both data types that allow to evaluate various dynamic and static observables based on the trajectories of the particles or the time evolution of continuum fields. For fast and efficient data handling, AMEP provides a unified framework for loading and storing simulation data and analysis results in a compressed, HDF5-based data format. AMEP is written purely in Python and uses powerful libraries such as NumPy, SciPy, Matplotlib, and scikit-image commonly used in computational physics. Therefore, understanding, modifying, and building up on the provided framework is comparatively easy. All evaluation functions are optimized to run efficiently on HPC hardware to provide fast computations. To plot and visualize simulation data and analysis results, AMEP provides an optimized plotting framework based on the Matplotlib Python library, which allows to easily plot and animate particles, fields, and lines. Compared to other analysis libraries, the huge variety of analysis methods combined with the possibility to handle both most common data types used in soft-matter physics and in the active matter community in particular, enables the analysis of a much broader class of simulation data including not only classical molecular-dynamics or Brownian-dynamics simulations but also any kind of numerical solutions of partial differential equations. The following table gives an overview on the observables provided by AMEP and on their capability of running in parallel and processing particle-based and continuum simulation data.

Observable Parallel Particles Fields
Spatial Correlation Functions:
RDF (radial pair distribution function)
PCF2d (2d pair correlation function)
PCFangle (angular pair correlation function)
SFiso (isotropic static structure factor)
SF2d (2d static structure factor)
SpatialVelCor (spatial velocity correlation function)
PosOrderCor (positional order correlation function)
HexOrderCor (hexagonal order correlation function)
Local Order:
Voronoi tesselation
Local density
Local packing fraction
k-atic bond order parameter
Next/nearest neighbor search
Time Correlation Functions:
MSD (mean square displacement)
VACF (velocity autocorrelation function)
OACF (orientation autocorrelation function)
Cluster Analysis:
Clustersize distribution
Cluster growth
Radius of gyration
Linear extension
Center of mass
Gyration tensor
Inertia tensor
Miscellaneous:
Translational/rotational kinetic energy
Kinetic temperature

Installation

The AMEP library can be installed via pip, conda, or by manually adding the amep directory to your Python path. Installation via pip or conda is recommended. To use all plot animation features, please additionally install FFmpeg (https://ffmpeg.org/) on your machine (see below).

Installation via pip

AMEP can be simply installed from PyPI via

pip install amep

Installation via conda

AMEP can be simply installed from conda-forge via

conda install conda-forge::amep

Manual installation

Before installing AMEP manually, ensure that your Python environment fulfills the required specifications as published together with each release. If your Python environment is set up, download the latest version from https://github.com/amepproject/amep and extract the zipped file. Then, add the path to your Python path and import amep:

import sys
sys.path.append('/path/to/amep-<version>')
import amep

Alternatively, you can add the path permanently to your Python path by adding the line

export PYTHONPATH="${PYTHONPATH}:/path/to/amep-<version>"

to the .bash_profile file (Linux only). If you use the Anaconda distribution, you can alternatively add the amep directory to Lib/site-packages in the Anaconda installation path.

FFmpeg

AMEP provides the possibility to animate plots and trajectories. To enable all animation features, FFmpeg must be installed on the device on which you run AMEP. FFmpeg is not automatically installed when you install AMEP. Please visit https://ffmpeg.org/download.html to download FFmpeg and to get further information on how to install FFmpeg on your machine.

Citation

If you use AMEP for a project that leads to a scientific publication, please acknowledge the use of AMEP within the body of your publication for example by copying or adapting the following formulation:

Data analysis for this publication utilized the AMEP library [1].

[1] L. Hecht, K.-R. Dormann, K. L. Spanheimer, M. Ebrahimi, M. Cordts, S. Mandal, A. K. Mukhopadhyay, and B. Liebchen, AMEP: The Active Matter Evaluation Package for Python, arXiv [Cond-Mat.Soft] (2024). Available at: http://arxiv.org/abs/2404.16533.

The pre-print is freely available on arXiv. To cite this reference, you can use the following BibTeX entry:

@misc{hecht2024amep,
    title = {AMEP: The Active Matter Evaluation Package for Python}, 
    author = {Lukas Hecht and 
              Kay-Robert Dormann and 
              Kai Luca Spanheimer and 
              Mahdieh Ebrahimi and 
              Malte Cordts and 
              Suvendu Mandal and 
              Aritra K. Mukhopadhyay and 
              Benno Liebchen},
    year = {2024},
    eprint = {2404.16533},
    archivePrefix = {arXiv},
    primaryClass = {cond-mat.soft}
}

Getting started

The following example briefly demonstrates the AMEP workflow. A typical task is to calculate the average of an observable over several frames of the simulation (time average). In the example below, we first load LAMMPS simulation data stored as individual dump*.txt files for each frame, and second, we calculate and plot the time-averaged radial pair distribution function (RDF).

# import the amep library
import amep

# load simulation data (creates an h5amep file and returns a trajectory object)
traj = amep.load.traj('./examples/data/lammps')

# calculate the radial pair-distribution function, skip the first half of the
# trajectory, and average over 10 frames with equal distance in time
rdf = amep.evaluate.RDF(traj, skip=0.5, nav=10, nbins=1000)

# save result in file
rdf.save('./rdf.h5')

# plot the result
fig, axs = amep.plot.new()
axs.plot(rdf.r, rdf.avg)
axs.set_title(amep.plot.to_latex(rdf.name))
axs.set_xlim(0,10)
axs.set_xlabel(r'$r$')
axs.set_ylabel(r'$g(r)$')
amep.plot.set_locators(axs, which='both', major=1, minor=0.2)
fig.savefig(rdf.name + '.png')
fig.savefig(rdf.name + '.pdf')

For more detailed examples, check the examples directory.

Module descriptions

In the following, we provide a list of all AMEP modules together with a short description.

Module: Description:
base.py base classes (backend)
cluster.py cluster analysis for particle-based data
continuum.py coarse-graining and continuum field analysis
evaluate.py trajectory analysis
functions.py mathematical functions and fitting
load.py loading simulation data and analysis results
order.py spatial order analysis
pbc.py handling of periodic boundary conditions
plot.py visualization and animation
reader.py simulation data reader (backend)
spatialcor.py spatial correlation functions
statistics.py statistical analysis
thermo.py thermodynamic observables
trajectory.py trajectory classes (backend)
utils.py collection of utility functions

Data Formats

AMEP is compatible with multiple data formats. The current version can load particle-based simulation data obtained from LAMMPS (https://www.lammps.org) and continuum simulation data with the following format: The main directory should contain one file with data that stays constant throughout the entire simulation such as the boundaries of the simulation box, the shape of the underlying grid and the grid coordinates. It's standard name is grid.txt and it should have the following form:

BOX:
<X_min>	<X_max>
<Y_min>	<Y_max>
<Z_min>	<Z_max>
SHAPE:
<nx> <ny> <nz>
COORDINATES: X Y Z
<X_0> <Y_0> <Z_0>
<X_1> <Y_1> <Z_1>
...

All data that varies in time is to be put into files named dump<index>.txt. The index should increase with time, i.e., the file dump1000.txt should contain the data of the continuum simulation at timestep 1000, and the prefix dump is user-defined and can be changed (if it is changed, the new naming convention has to be specified with the keyword dumps in amep.load.traj, e.g., for files named field_100.txt, field_200.txt, ..., use dumps='field_*.txt'). The data files should have the following form:

TIMESTEP:
<Simulation timestep>
TIME:
<Physical time>
DATA: <fieldname 0> <fieldname 1> <fieldname 2> <fieldname 3>
<field 0 0> <field 1 0> <field 2 0> <field 3 0>
<field 0 1> <field 1 1> <field 2 1> <field 3 1>
<field 0 2> <field 1 2> <field 2 2> <field 3 2>
...

Support

If you need support for using AMEP, we recommend to use our GitHub discussions page. If you find a bug, please create an issue.

Creating issues

To create an issue, go to https://github.com/amepproject/amep/issues and click on New issue. Then, continue with the following steps:

  1. Add a short and clear title.
  2. Write a precise description of the bug which you found. If you got an error message, add it to the description together with a short code snippet with which you can reproduce the error.
  3. If it is already known how the bug can be fixed, please add a short to-do list to the description.

When creating issues, text is written as markdown, which allows formatting text, code, or tables for example. A useful guide can be found here.

Roadmap

Planned new features for future releases are listed as issues in the issue list.

Contributing

If you want to contribute to this project, please check the file CONTRIBUTING.md.

Contributors/Authors

The following people contributed to AMEP:

  • Lukas Hecht (creator and lead developer)
  • Kay-Robert Dormann (developer)
  • Kai Luca Spanheimer (developer)
  • Aritra Mukhopadhyay (developer)
  • Mahdieh Ebrahimi (developer)
  • Suvendu Mandal (developer)
  • Benno Liebchen (planning)
  • Lukas Walter (former developer)
  • Malte Cordts (former developer)

Acknowledgments

Many thanks to the whole group of Benno Liebchen at the Institute for Condensed Matter Physics at Technical University of Darmstadt for testing and supporting AMEP, for fruitful discussions, and for very helpful feedback. Additionally, the authors gratefully acknowledge the computing time provided to them at the NHR Center NHR4CES at TU Darmstadt (project number p0020259). This is funded by the Federal Ministry of Education and Research, and the state governments participating on the basis of the resolutions of the GWK for national high performance computing at universities (https://www.nhr-verein.de/unsere-partner).

License

The AMEP library is published under the GNU General Public License, version 3 or any later version. Please see the file LICENSE for more information.

amep's People

Contributors

hechtprojects avatar kai-luca avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

descho00 hjc19

amep's Issues

DOC: incorrect spatialcor.pcf_angle example

Problem description:

https://amepproject.de/_autosummary/amep.spatialcor.pcf_angle.html

Within the example, the line import numpy as np is missing. Additionally, the plotting is incorrect.

Suggested content improvement:

Add >>> import numpy as np to the example in the doc string of amep.spatialcor.pcf_angle.

Replace the line mp = amep.plot.field(axs, grt, X, Y) with mp = amep.plot.field(axs, grt.T, X, Y) and add the resulting figure to the documentation.

DOC: evaluate.VelDist missing keyword argument description

Problem description:

The documentation of the VelDist evaluation class is missing the description of several keyword arguments, namely vmin, vmax, v2max. The description how the limits of the distribution for v² and |v| are being calculated is missing.

Moreover, the calculation of the upper limit of the distribution for v² and |v|is unclear.

Suggested content improvement:

  • extend class call with type hints
  • add missing descriptions of keyword arguments in documentation
  • potentially fix the calculation for the upper limits of the distribution for v² and |v| - or document behavior thoroughly

BUG: h5amep format improvements - no zero-padding in h5amep file

Description:

At the moment, the LAMMPS reader reads dump files and and stores the data in the h5amep file. Data such as coordinates or velocities are stored as 3d data. Data that is missing (such as z in 2d simulations) is replaced by 0s. But this may not always be correct. If the simulation data is missing a component accidentally, this would lead to incorrect replacement of missing data.

This also applies to the current version of the AMEP HDF5 data format. It combines all vector quantities to a 3d dataset in the h5amep file, e.g., coordinates are stored as a (N,3) dataset named 'coords'. If for a 2d system for example, only x and y are given, the z component will automatically be set to zero. Additionally, the h5amep file will have datasets for all standard vector quantities initialized with zeros per default. Thus, even if for exameple forces are not given in the dump files, a dataset called "forces" exists that only contains zeros. It would be better, if it would not exist. Additionally, if the user wants to access this data, an error should be raised saying that the requested data is not availabe.

In conclusion, we should not initialize the HDF5 file with arrays of zeros. Instead, it would be better to store each quantity (i.e., each column of a dump file) in a seperate dataset (as already done for the scalar quantities and any user-defined quantities). Thus, instead of 'coords', the HDF5 file will have 3 datasets called 'x', 'y', and 'z' (if all of them are given in the dump file). If for example z is not given, there will be no dataset called 'z'.

If the user wants to access the data, e.g., if one would like to get the coordinate array in the shape (N,3) and for example z does not exist, AMEP should fill the last column of the array with zeros and print a warning (same for other vector quantities such as velocities, forces, ...).

Backwards compatibility can be ensured by modifying the __read_data method of the BaseFrame class (we need an additional if condition such that we will have two, one for the current format and one for the new format).

Code for reproduction:

traj = amep.load.traj("2d_data", mode="lammps")
coords = traj[-1].coords()
print(coords[:,2])

Error message:

Output should not be 0s. At least a warning is expected.

Python and AMEP versions:

any python version, AMEP 1.0.1

Additional information:

ToDo:

  • adapt all particle-based reader classes to generate HDF5 files with the new format
    • check which data is stored incorrectly (coordinates, velocities, ...)
    • store only imported data
    • implement warning/... if missing data is replaced with 0s on import
  • adapt BaseFrame.__read_data and BaseFrame.data to handle both formats for backwards compatibility
  • test the new format (i.e., generate a new h5amep file and check with an HDF5 viewer if the format is correct)
  • test all AMEP methods that allow to access the data (i.e., all methods of BaseFrame)
  • test implementation for backwards-compatibility

How did you install AMEP?

None

FRQ: allow user to supply part of a trajectory as trajectory

Proposed new feature or change:

Rather than having to supply a full trajectory, it would be useful if the user also can only supply parts of it.

traj[:100:] or traj[::2] currently do not work because the required type in most functions is FieldTrajectory | ParticleTrajectory rather than list | iterable of Frame. If a subset of a trajectory is still returned as a trajectory, traj[i] should still return the ith frame and not a trajectory of length 1 (for compatibility!).

Implementation principle:

class A:
    def __init__(self, liste, sl=None):
        self.__liste=liste
        self.__allitems=np.arange(len(liste))
        if sl is None:
            self.__sl=slice(0,len(liste),1)
        else:
            self.__sl=sl
    def __getitem__(self, item):
        if isinstance(item, int):
            item = self.__allitems[self.__sl][item]
            return self.__liste[item]
        elif isinstance(item, slice):
            # -> convert slice to list
            # create class A from sl=sl-list[item]
            # (np.arange(100)[slice(0,10,1)])[slice(0,6,2)]
            return A(self.__liste, sl=item)
        elif isinstance(item, list):
            # create class A from sl=sl[item]
            return A(self.__liste, sl=item)
    def __iter__(self):
        for i in range(len(self.__liste[self.__sl])):
            yield self[i]
    def __len__(self):
        return len(self.__liste[self.__sl])

a = A(np.arange(0,100,1))

print(len(a), type(a), a[13])
b = a[[1,6,3]]
print(len(b), type(b), b[1])
c = b[::2]
print(len(c), type(c), c[13])
100 <class '__main__.A'> 13
3 <class '__main__.A'> 6
50 <class '__main__.A'> 26

FRQ: Dynamical structure factor

Proposed new feature or change:

It turns out that a dynamical structure factor is not only really useful for glassy people but also for my breathing particles.
So I'm gonna start to implement this.
But first I'll have to read up a bit.

BUG: evaluate.Psi6dist number of bins default causes error

Description:

Similar issue to #32.
If the class gets a trajectory with fewer than 100 particles, the number of bins is set to 0 by default. This causes an unexpected behavior of the distribution function.

Code for reproduction:

import amep
traj = amep.load.traj("../examples/data/lammps.h5amep")
ld1 = amep.evaluate.Psi6dist(traj)

Error message:

No response

Python and AMEP versions:

any python version, AMEP 1.0.2

Additional information:

Can be easily fixed by setting the default number of bins nbins to 50 (analogous to the similar fix in evaluate.LDDist)

  • set nbins=50
  • update documentation

How did you install AMEP?

None

FRQ: chemfiles reader.

Proposed new feature or change:

To enable the loading of various simulation data formats, AMEP should provide a new reader class based on the Chemfiles Python library (https://chemfiles.org/). This new reader class should be implemented as ChemfilesReader in the module amep.reader. It should convert the loaded data to the .h5amep format.

BUG: trajectory add/get_particle_info() not compatible with strings

Description:

When saving particle type info in the trajectory file, a string can be used as ptype. But when trying to get the info, an error occurs due to the reader expecting an int instead of a string.

Code for reproduction:

import amep
traj_particles=amep.load.traj(path_particles, reload=True)
traj_particles.add_particle_info(1, "key", "value")
traj_particles.add_particle_info("asdf", "key2", "value2")
traj_particles.get_particle_info()

Error message:


ValueError Traceback (most recent call last)
Cell In[27], line 1
----> 1 traj_particles.get_particle_info()

File ~/Documents/git_amep/amep/trajectory.py:233, in ParticleTrajectory.get_particle_info(self, ptype)
231 p = {}
232 for t in list(root['particles'].keys()):
--> 233 p[int(t)] = dict(a for a in root['particles'][t].attrs.items())
234 elif str(ptype) in list(root['particles'].keys()):
235 p = dict(a for a in root['particles'][str(ptype)].attrs.items())

ValueError: invalid literal for int() with base 10: 'asdf'

Python and AMEP versions:

1.0.2_dev (github version 10.7.2024), python 3.10

Additional information:

traj_particles.add_particle_info(ptype, key, value)
  • Allow only int-ptype.
  • Fix amep.trajectory.ParticleTrajectory
  • traj_particles.get_particle_info(ptype) should only return info for ptype=int.

How did you install AMEP?

None

FRQ: update/append trajectory

Proposed new feature or change:

To extend an existing trajectory with additional simulation data, it would be useful to be able to append frames to an existing trajectory. Since the trajectory object already has similar properties as a list, we can define an append methods similar to the one for lists. This also allows to update a trajectory for extended data.

ToDo:

  • implement the append method in BaseTrajectory
  • add extend=False keyword to LammpsReader and ContinuumReader
  • if True, the reader checks whether new dump files are in the directory of the h5amep file and if so, it adds those to the h5amep file
  • make compatible with minor release!
  • decide on approach
    • implement a update method in BaseTrajectory or
    • alternative: add update keyword to load.traj(...)
  • write a short test method for the unit tests
  • update documentation
  • write short example(s)

BUG: distutils - incompatibility with Python 3.12

Description:

The distutils library is used in the module amep.plot but is not part of Python 3.12 anymore. Therefore, using AMEP within Python 3.12 raises an error.

Code for reproduction:

import amep

Error message:

image

Python and AMEP versions:

python 3.12
amep 1.0.0

Additional information:

Solution:

  1. Replace from distutils.spawn import find_executable with from shutil import which.

  2. Replace if find_executable('latex'): with if which('latex'):.

How did you install AMEP?

pip

BUG: 'exclude' option does not work for 'order.nearest_neighbors' and 'order.k_nearest_neighbors' when 'other_coords' is specified

Description:

order.nearest_neighbors and order.k_nearest_neighbors counts the particle itself when counting its neighbors when other_coords is specified explicitly.

Code for reproduction:

import amep

traj = amep.load.traj('./examples/data/lammps')
frame = traj[-1]

# calculate nearest neighbours of particle id 2
nnn, distances, neighbors = amep.order.nearest_neighbors(
    frame.coords()[2, None], frame.box, other_coords=frame.coords(), exclude=True, pbc=True
)

#nnn, distances, neighbors = amep.order.k_nearest_neighbors(
#    frame.coords()[2, None], frame.box, other_coords=frame.coords(), pbc=True
#)

print(nnn) # number of nearest neighbors
print(distances) # nearest-neighbor distances
print(neighbors) # nearest neighbor ids

Error message:

No response

Python and AMEP versions:

Python 3.12.3
AMEP 1.0.1

Additional information:

No response

How did you install AMEP?

conda

FRQ: lattice function

Proposed new feature or change:

The local density in particle simulations is calculated at the locations of the particles but in cases where there MIPS is collapse-like, this causes a sometimes unwanted underrepresentation of the gaseous phase. One option is to calculate the local density by first calculating a density field from the particle simulations but this is computationally expensive in large simulations. An alternative is to use the same method as with the local density but evaluate at evenly spaced grid points throughout the simulation box.

To do so, a lattice function should should be implemented that allows to calculate the coordinates of specific lattices in 2D (and 3D). A square grid should be the focus. The user should be able to give a number of points or a specific number of grid points in all directions.

ToDo:

  • add function amep.utils.lattice (gets number of lattice points and box)
  • add detailed documentation
  • detailed testing of the module to verify the created lattices
  • add example (also to calculation of local density distribution) where the lattice is used to calculate the local density distribution

BUG: fixed fps in plot.animate_trajectory

Description:

When using amep.plot.animate_trajectory, the output video has a relatively low fps. For the user, it is not possible to change the fps value.

Code for reproduction:

import amep

traj = amep.load.traj('.')

amep.plot.animate_traj(traj, './video.mp4')

Error message:

No response

Python and AMEP versions:

python 3.10
amep 1.0.1

Additional information:

A new keyword fps=10 should be added to amep.plot.animate_trajectory. It should also be forwarded in traj.animate.

How did you install AMEP?

from source

FRQ: Plot arrows for annotations.

Proposed new feature or change:

Add the following method (+ docstring + example) to amep.plot:

def draw_arrow(fig, x, y, dx, dy, **kwargs):
    arrow = FancyArrow(x, y, dx, dy, transform=fig.transFigure, length_includes_head=True, **kwargs)
    fig.add_artist(arrow)

This allows to draw an arrow that points from (x, y) to (x+dx, y+dy), which is useful for annotation purposes.

BUG: `evaluate.ClusterGrowth` does not work with fields

Description:

The ClusterGrowth functionality does not work. It just throws an error because it still wants to use an old version of the field cluster detection.

Code for reproduction:

from amep import load
from amep.evaluate import ClusterGrowth
f_traj = load.traj(<Field_trajectory_path>)
ClusterGrowth(

Error message:

Traceback (most recent call last):
File "/home/kspanheimer/Documents/dev/amep_project/amep_data/amep_publication_plots/gen_cluster_data.py", line 146, in
gen_growth_data(field_trajectories)
File "/home/kspanheimer/Documents/dev/amep_project/amep_data/amep_publication_plots/gen_cluster_data.py", line 72, in gen_growth_data
wmea_c_grow = np.stack([ClusterGrowth(trajec,
^^^^^^^^^^^^^^^^^^^^^^
File "/home/kspanheimer/Documents/dev/amep_project/amep_data/amep_publication_plots/gen_cluster_data.py", line 72, in
wmea_c_grow = np.stack([ClusterGrowth(trajec,
^^^^^^^^^^^^^^^^^^^^^
File "/home/kspanheimer/Documents/dev/amep_project/amep/amep/evaluate.py", line 3538, in init
self.__frames, self.__avg, self.__indices = average_func(
^^^^^^^^^^^^^
File "/home/kspanheimer/Documents/dev/amep_project/amep/amep/utils.py", line 141, in average_func
func_result = [func(x, **kwargs) for x in tqdm(data[evaluated_indices])]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/kspanheimer/Documents/dev/amep_project/amep/amep/utils.py", line 141, in
func_result = [func(x, **kwargs) for x in tqdm(data[evaluated_indices])]
^^^^^^^^^^^^^^^^^
File "/home/kspanheimer/Documents/dev/amep_project/amep/amep/evaluate.py", line 3612, in __compute_fields
ids, labels = identify_clusters(
^^^^^^^^^^^^^^^^^^
TypeError: identify_clusters() got an unexpected keyword argument 'field'

Python and AMEP versions:

Python 3.11.9
AMEP 1.0.0

Additional information:

I won't add all the reproducabillity etc. since I'll fix it myself.

How did you install AMEP?

pip

FRQ: extend functionality of frame.data() to accept lists

Proposed new feature or change:

The Frame s of Trajectory objects store all data and specific values can be extracted with frame.data() by supplying the wanted keys as arguments. But often it is easier to supply a list or array of keys which is not possible at the moment, therefore it would help to add a recursive call at the beginning of the function to accept lists as well as arguments.

if isinstance(args, (list, np.ndarray)):
    return data(self, *args, ptype = ptype, zerofill = zerofill, return_keys = return_keys)
  • implement and check implementation
  • update documentation
  • add example

FRQ: simplify how to set the plot style in plot.style()

Proposed new feature or change:

The call of the amep.plot.style() function is different for whether the goal is to set an amep style or the default matplotlib style. To make this functionality more user-friendly, the labels for the styles can be simplified and one added for the default matplotlib style.
The following changes would simplify the usage:

  • "amep_latex" -> "latex"
  • "amep_standard" -> "standard"
  • mpl_default=True -> "matplotlib"

When updating the code in compliance with a minor release, please keep it backwards-compatible.
Additionally, prepare for a major release with the simplified call arguments by adding a note to the documentation:

.. note:: Deprecates in 2.0.0
          `mpl_default` will be removed in an upcoming major release. Please use "matplotlib".
          "amep_latex" and "amep_standard" will be removed. Please use "latex" and "standard" instead.

BUG: MSD calculation not possible with pbc=True if no unwrapped coords available

Description:

The data availability checks in amep.evaluate.MSD are not compatible with the current unwrapped_coords and nojump_coords methods of a BaseFrame object. Therefore, the checks themselves raise an error and do not allow to calculate the MSD using nojump coordinates for example.

Code for reproduction:

traj = amep.load.traj(
    "./data",
    mode = "lammps",
    dumps = "*.txt"
)
traj.nojump()

msd = amep.evaluate.MSD(traj, pbc=True, use_nojump=True)

Error message:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[27], line 1
----> 1 msd = amep.evaluate.MSD(traj, pbc=True, use_nojump=True)

File D:\amep\evaluate.py:3812, in MSD.__init__(self, traj, ptype, skip, nav, use_nojump, pbc)
   3807 if self.__use_nojump and self.__traj[0].nojump_coords() is None:
   3808     raise ValueError(
   3809         'No nojump coordinates available. Call traj.nojump() '\
   3810         'to calculate the nojump coordinates.'
   3811     )
-> 3812 elif self.__pbc and self.__traj[0].unwrapped_coords() is None\
   3813 and self.__traj[0].nojump_coords() is None:
   3814     raise ValueError(
   3815         'Neither unwrapped nor nojump coordinates are available. '\
   3816         'Call traj.nojump() to calculate the nojump coordinates or '\
   3817         'do not apply periodic boundary conditions.'
   3818     )
   3819 else:
   3820     # get mode

File D:\amep\base.py:582, in BaseFrame.unwrapped_coords(self, **kwargs)
    566 def unwrapped_coords(self, **kwargs) -> np.ndarray:
    567     """
    568     Returns the unwrapped coordinates of all particles or of 
    569     all particles of a specific particle type.
   (...)
    580 
    581     """
--> 582     return self.__read_data("uwcoords",**kwargs)

File D:\amep\base.py:967, in BaseFrame.__read_data(self, key, ptype, pid)
    964     return data[mask.astype(bool)]
    966 else:
--> 967     raise KeyError(
    968         f"The key {key} does not exist in the frame. "\
    969         "Returning no data!"
    970     )

KeyError: 'The key uwcoords does not exist in the frame. Returning no data!'

Python and AMEP versions:

Python 3.10
AMEP 1.0.1

Additional information:

The data availability checks in amep.evaluate.MSD.__init__ could be done as follows:

# check data availability
        if self.__pbc:
            if self.__use_nojump:
                try:
                    a = self.__traj[0].nojump_coords()
                except:
                    raise ValueError(
                        'No nojump coordinates available. Call traj.nojump() '\
                        'to calculate the nojump coordinates.'
                    )
            else:
                try:
                    a = self.__traj[0].unwrapped_coords()
                except:
                    raise ValueError(
                        'There are no unwrapped coordinates available. '\
                        'Please set use_nojump=True to use nojump coordinates instead '\
                        'or do not apply periodic boundary conditions.'
                    )
        # get mode
        if self.__pbc and self.__use_nojump:
            self.__mode = 'nojump'
        elif self.__pbc:
            self.__mode = 'unwrapped'
        else:
            self.__mode = 'normal'

How did you install AMEP?

from source

BUG: Change of timestep does not lead to a change of the physical time

Description:

A new timestep set by traj.dt = <timestep> does not affect traj.times.

Code for reproduction:

import amep
traj = amep.load.traj(<path-to-traj>)
traj.dt = <timestep>
print(traj.times)

Error message:

No response

Python and AMEP versions:

AMEP: 1.0.0
Python: 3.12.2

Additional information:

No response

How did you install AMEP?

conda

FRQ: Stress tensor and mechanical pressure.

Proposed new feature or change:

The (local) stress tensor can easily be calculated from simulation data using the Irving-Kirkwood stress tensor [1]. It can also be applied to non-equilibrium systems as shown in Ref. [2] (see Eq. 2). From the stress tensor, one can then calculate the mechanical pressure from its trace.

We should add this feature (stress tensor and pressure calculation) to AMEP's thermo module.

[1] https://pubs.aip.org/aip/jcp/article/18/6/817/201367/The-Statistical-Mechanical-Theory-of-Transport
[2] https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.132.168201

DOC: Incorrect description of 'coords' and 'other_coords' in 'order.nearest_neighbors' and 'order.k_nearest_neighbors'

Problem description:

These two descriptions should be interchanged:

coords (np.ndarray of shape (N,3)) – Array of coordinates/points to search for neighbors.

other_coords (np.ndarray of shape (M,3) or None, optional) – Array of points to search for neighbors of. The default is None (use coords).

Suggested content improvement:

Should read:

coords (np.ndarray of shape (N,3)) – Array of points to search for neighbors of.

other_coords (np.ndarray of shape (M,3) or None, optional) – Array of coordinates/points to search for neighbors. The default is None (use coords).

FRQ: generalize utils.mesh_to_coords to 3D

Proposed new feature or change:

Currently utils.mesh_to_coords() only works with two dimensions. For 3d simulations it would be useful to handle other numbers of dimensions as well.

Here is a first idea of how to generalize the function, where g=[x,y,z] is a multi-dimensional array. It should still be necessary to give x, y and z separately instead of just one array g.

positions = np.array([a.ravel() for a in g]).T

BUG: evaluate.VelDist number of bins default causes error

Description:

If the VelDist class of the evaluate module gets a trajectory with fewer than 100 particles, the number of bins is set to 0 by default. This causes an unexpected behavior of the distribution function.

Code for reproduction:

import amep
traj = amep.load.traj("../examples/data/lammps.h5amep")
ld1 = amep.evaluate.VelDist(traj)

Error message:

No response

Python and AMEP versions:

any python version, AMEP 1.0.2

Additional information:

Can be easily fixed by setting the default number of bins nbins to 50 (analogous to the similar fix in evaluate.LDDist)

  • set nbins=50
  • update documentation

How did you install AMEP?

None

FRQ: h5amep format update for constant data

Proposed new feature or change:

  • Create a new group in h5amep that replaces the particles group and saves constant information about the particles such as mass, radius, charge, ...
  • This data should be accessible via the frame.data(...) method.
  • get_particle_info() and add_particle_info() will be removed.
  • Add possibility to return data for specific molecules/atoms/residues/... similar to gromacs
    image

DOC: Trajectories not referencing to BaseFrame/BaseField

Problem description:

In the documentation of the ParticleTrajectory and FieldTrajectory there does not exist a reference to BaseFrame or BaseField respectively. This makes it hard to understand how to get information from the trajectory objects.

Suggested content improvement:

  • Add clickable link to the individual frame types (BaseFrame or BaseField) to the docstring.
  • Also, add a __get_item__ documentation.

BUG: LammpsReader angmom not imported

Description:

In reader.LammpsReader the angular momentum is read from the dump files but there is no dataset created in the h5amep file.

Code for reproduction:

traj[0].angmom()

Error message:

No response

Python and AMEP versions:

amep 1.0.2

Additional information:

No response

How did you install AMEP?

None

FRQ: Support for gsd files. Format of hoomd-blue

Proposed new feature or change:

Since I'm looking into hoomd-blue and this is a widely used simulation suite I would like to include support for hoomd-blue in AMEP.
They already got a python library so the only thing we have to do is translate to AMEP.

DOC: Documentation for fit functions should include mathematical expression

Problem description:

The fit functions do fit mathematical functions to data. But there are not given any mathematic expression since we seem to expect that people know what a Maxwell-Boltzmann distribution is.

Suggested content improvement:

For all predefined fit functions the mathematical expression of that function should be included in the documentation.

FRQ: Test Suite based on the example dataset

Proposed new feature or change:

We would like our test suite to only depend on the example dataset included in the repository.
This should be possible by removing the dummy data creation and downloads, as well as rewriting the data initialization for each test case so it uses our data.
Also we should increase our test coverage.

FRQ: local entropy production

Proposed new feature or change:

AMEP should provide a method to calculate the local entropy production, which is an important observable for investigating active matter systems. I suggest to implement the method presented in Ref. [1], the source code of which can be found in Ref. [2]. It is a universal method that does not require any knowledge about the equations of motions and should applicable to both particle-based and continuum simulation data as well as experimental data.

The method should be included in the module amep.thermo and a corresponding evaluate class should also be added to the amep.evaluate module.

[1] https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.129.220601

[2] https://github.com/martiniani-lab/sweetsourcod/tree/master

FRQ: gsd/gromacs reader - basic features

Proposed new feature or change:

Basic features of gsd and gromacs readers to be implemented in AMEP as a minor release:

  • gsd reader
  • gromacs reader (#13)
  • molecule identifier

The new data such as molecule_id, molecule_type will be saved in the h5amep format as dataset in each frame.

(id) type mol_id mol_type charge coordinates ...
(1)    c1    1           coh            0.29      ....
2      c2    1           coh            0.0      ....
3      o1    1           coh            0.0      ....
4      h1    1           coh            -0.29      ....
5      c1    2           coh            0.29      ....
6      c2    2           coh            0.0      ....
7      o1    2           coh            0.0      ....
8      h1    2           coh            -0.29      ....
...

DOC: examples for load.traj

Problem description:

There are no examples for loading continuum data in load.traj().

Suggested content improvement:

Update the examples and add one for continuum data. Preferably to be consistent with the examples provided in examples/data/continuum.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.