matpes 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
matpes/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Tools for working with MatPES."""
2
+
3
+ from __future__ import annotations
4
+
5
+ MATPES_SRC = "https://mavrl-web.s3.us-east-1.amazonaws.com/matpes"
matpes/cli.py ADDED
@@ -0,0 +1,166 @@
1
+ """
2
+ This module implements a CLI for MatPES, a material property exploration suite.
3
+
4
+ The CLI provides the following features:
5
+ - Download functionality to fetch data related to specific functionals using the `download` command.
6
+ - Data processing capabilities using the `data` command, including filtering MatPES data by
7
+ chemical systems or formulas.
8
+
9
+ The commands are structured as subcommands, facilitating distinct functionalities for
10
+ data retrieval and post-processing operations.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+
18
+ from monty.io import zopen
19
+ from pymatgen.core import Composition
20
+
21
+ from .data import get_data
22
+
23
+
24
+ def download(args):
25
+ """
26
+ Function to download data based on the given functional argument.
27
+
28
+ This function utilizes the "get_data" method with an input argument
29
+ to fetch and download data tied to the specified functionality. After
30
+ successful execution, it outputs a confirmation message.
31
+
32
+ Parameters
33
+ ----------
34
+ args : argparse.Namespace
35
+ Argument namespace that must contain a "functional" attribute.
36
+
37
+ Raises:
38
+ ------
39
+ None
40
+ """
41
+ get_data(functional=args.functional)
42
+ print(f">>> Successfully downloaded data for {args.functional}.")
43
+
44
+
45
+ def get_data_subset(args):
46
+ """
47
+ Filter MatPES data by chemical system or formula.
48
+
49
+ This function processes a given JSON file containing MatPES data and filters
50
+ the entries based on chemical systems or formulas specified by the user.
51
+ The filtered results are then written to an output file.
52
+
53
+ Parameters:
54
+ args: Namespace
55
+ A namespace object containing the following attributes:
56
+ - filename: List[str]
57
+ List containing the name of the input file to process (only
58
+ the first entry is used).
59
+ - outfile: str
60
+ Name of the output file to write the filtered results to.
61
+ Defaults to 'filtered.json.gz'.
62
+ - chemsys: List[str]
63
+ List of chemical systems (e.g., 'Li-Fe-O') to filter by.
64
+ If empty, no filtering by chemical system is applied.
65
+ - formula: List[str]
66
+ List of formulas (e.g., 'Fe2O3') to filter by. If empty,
67
+ no filtering by formula is applied.
68
+
69
+ Returns:
70
+ None
71
+
72
+ Notes:
73
+ - The chemical system string should follow the format 'Element1-Element2-...'.
74
+ - Formulas are case-insensitive and automatically converted to their
75
+ reduced forms for comparison.
76
+ - The input file must be a JSON file and the output is written in
77
+ compressed JSON format.
78
+ """
79
+ infname = args.filename[0]
80
+ outfname = args.outfile
81
+ with zopen(infname, "rt", encoding="utf-8") as f:
82
+ data = json.load(f)
83
+ print(f"Total number of entries: {len(data)}.")
84
+ if args.chemsys:
85
+ for c in args.chemsys:
86
+ chemsys = "-".join(sorted(c.split("-")))
87
+ data = [d for d in data if d["chemsys"] == chemsys]
88
+ if args.formula:
89
+ for f in args.formula:
90
+ f = Composition(f).reduced_formula
91
+ data = [d for d in data if d["formula_pretty"] == f]
92
+ with zopen(outfname, "wt", encoding="utf-8") as f:
93
+ json.dump(data, f)
94
+ print(f"{len(data)} filtered entries written in {outfname}.")
95
+
96
+
97
+ def main():
98
+ """Main entry point for matpes cli."""
99
+ parser = argparse.ArgumentParser(
100
+ description="""matpes is a CLI for MatPES.""",
101
+ epilog="Author: Shyue Ping Ong",
102
+ )
103
+
104
+ subparsers = parser.add_subparsers()
105
+ subparser_download = subparsers.add_parser(name="download")
106
+ subparser_download.add_argument(
107
+ "functional",
108
+ metavar="functional",
109
+ type=str.upper,
110
+ nargs="?",
111
+ default="PBE",
112
+ help="Functional to download. Defaults to PBE.",
113
+ )
114
+
115
+ subparser_download.set_defaults(func=download)
116
+
117
+ subparser_data = subparsers.add_parser(
118
+ name="data", help="Process downloaded MatPES data files, e.g., filtering by chemical system or formula."
119
+ )
120
+
121
+ subparser_data.add_argument(
122
+ "-f",
123
+ "--formula",
124
+ dest="formula",
125
+ type=str,
126
+ nargs="*",
127
+ help="Formulas to filter by, e.g., Fe2O3.",
128
+ )
129
+
130
+ subparser_data.add_argument(
131
+ "-c",
132
+ "--chemsys",
133
+ dest="chemsys",
134
+ type=str,
135
+ nargs="*",
136
+ help="Chemical systems to filter by, e.g., Li-Fe-O.",
137
+ )
138
+
139
+ subparser_data.add_argument(
140
+ "-o",
141
+ "--outfile",
142
+ dest="outfile",
143
+ type=str,
144
+ nargs="?",
145
+ default="filtered.json.gz",
146
+ help="File to write filtered entries to.",
147
+ )
148
+
149
+ subparser_data.add_argument(
150
+ "filename",
151
+ metavar="filename",
152
+ type=str,
153
+ nargs=1,
154
+ help="Filename to process.",
155
+ )
156
+
157
+ subparser_data.set_defaults(func=get_data_subset)
158
+
159
+ args = parser.parse_args()
160
+
161
+ try:
162
+ _ = args.func
163
+ except AttributeError as exc:
164
+ parser.print_help()
165
+ raise SystemExit("Please specify a command.") from exc
166
+ return args.func(args)
matpes/data.py ADDED
@@ -0,0 +1,47 @@
1
+ """Methods for working with MatPES data downloads."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import json
7
+ import os
8
+ from typing import Literal
9
+
10
+ import requests
11
+
12
+ from matpes import MATPES_SRC
13
+
14
+
15
+ def get_data(functional: Literal["PBE", "R2SCAN"] = "PBE", version="20240214"):
16
+ """
17
+ Downloads and reads a JSON dataset file if not already present locally. The file
18
+ is expected to be hosted at a remote location, and the function will use the
19
+ specified functional and version to construct the file name. If the file is
20
+ not found locally, it will attempt to download the file, save it locally in
21
+ compressed format, and then load its contents.
22
+
23
+ Parameters:
24
+ functional (str): The functional type used for labeling the dataset.
25
+ Defaults to "PBE".
26
+ version (str): The version string for the dataset. Defaults to "20240214".
27
+
28
+ Returns:
29
+ dict: A dictionary representation of the JSON dataset contents.
30
+
31
+ Raises:
32
+ RuntimeError: If the file download fails or the remote source is
33
+ inaccessible.
34
+ """
35
+ fname = f"MatPES-{functional.upper()}-{version}.json.gz"
36
+
37
+ if not os.path.exists(fname):
38
+ url = f"{MATPES_SRC}/{fname}"
39
+ response = requests.get(url, stream=True)
40
+ if response.status_code == 200:
41
+ with open(fname, "wb") as file:
42
+ for chunk in response.iter_content(chunk_size=8192):
43
+ file.write(chunk)
44
+ else:
45
+ raise RuntimeError(f"Failed to download {url}. Status code: {response.status_code}")
46
+ with gzip.open(fname, "r") as f:
47
+ return json.load(f)
matpes/db.py ADDED
@@ -0,0 +1,110 @@
1
+ """Tools for directly working with a MatPES style DB."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ import pandas as pd
8
+ from pymongo import MongoClient
9
+
10
+ from .data import get_data
11
+
12
+
13
+ class MatPESDB:
14
+ """A MatPES DB object. This requires access to a MatPES style DB. Typically meant for developers."""
15
+
16
+ FUNCTIONALS = ("PBE", "r2SCAN")
17
+
18
+ def __init__(self, dbname="matpes"):
19
+ """
20
+ Args:
21
+ dbname (str): The name of the MatPES DB.
22
+ """
23
+ client = MongoClient(
24
+ host=os.environ.get("MATPES_HOST", "127.0.0.1"),
25
+ username=os.environ.get("MATPES_USERNAME"),
26
+ password=os.environ.get("MATPES_PASSWORD"),
27
+ authSource="admin",
28
+ )
29
+ self.db = client.get_database(dbname)
30
+
31
+ def create_db(self):
32
+ """
33
+ Create a MatPES database from the json files.
34
+ Note that any existing collections will be deleted.
35
+ """
36
+ for functional in self.FUNCTIONALS:
37
+ data = get_data(functional=functional)
38
+ coll = self.db.get_collection(functional.lower())
39
+ coll.delete_many({})
40
+ coll.insert_many(data)
41
+ for field in [
42
+ "matpes_id",
43
+ "formula_pretty",
44
+ "elements",
45
+ "chemsys",
46
+ "cohesive_energy_per_atom",
47
+ "nsites",
48
+ "nelements",
49
+ "bandgap",
50
+ ]:
51
+ coll.create_index(field)
52
+
53
+ def get_json(self, functional: str, criteria: dict) -> list:
54
+ """
55
+ Args:
56
+ functional (str): The name of the functional to query.
57
+ criteria (dict): The criteria to query.
58
+ """
59
+ return list(self.db.get_collection(functional.lower()).find(criteria))
60
+
61
+ def get_df(self, functional: str, criteria=None, projection=None) -> pd.DataFrame:
62
+ """
63
+ Retrieve a pandas DataFrame from a MongoDB collection based on the provided
64
+ criteria and projection.
65
+
66
+ This method queries a MongoDB collection corresponding to the specified
67
+ functional argument. It uses given criteria and projection to filter and
68
+ retrieve the desired data, returning the results in the form of a pandas
69
+ DataFrame. If no criteria or projection is provided, it uses default values.
70
+
71
+ Parameters:
72
+ functional: str
73
+ The name of the collection to query, corresponding to a specific
74
+ functional. The string is converted to lowercase.
75
+ criteria: dict, optional
76
+ A dictionary to filter the query results. Defaults to an empty
77
+ dictionary if not provided.
78
+ projection: list[str], optional
79
+ A list of strings specifying the fields to include in the query
80
+ results. Defaults to a predefined list of fields if not provided.
81
+
82
+ Returns:
83
+ pd.DataFrame
84
+ A pandas DataFrame containing the retrieved data with the specified
85
+ projection fields.
86
+
87
+ Raises:
88
+ None
89
+ """
90
+ collection = self.db.get_collection(functional.lower())
91
+ criteria = criteria or {}
92
+ projection = projection or [
93
+ "matpes_id",
94
+ "formula_pretty",
95
+ "elements",
96
+ "energy",
97
+ "chemsys",
98
+ "cohesive_energy_per_atom",
99
+ "formation_energy_per_atom",
100
+ "abs_forces",
101
+ "nsites",
102
+ "nelements",
103
+ "bandgap",
104
+ ]
105
+ return pd.DataFrame(
106
+ collection.find(
107
+ criteria,
108
+ projection=projection,
109
+ )
110
+ )[projection]
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2022, Materials Virtual Lab
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.2
2
+ Name: matpes
3
+ Version: 0.0.1
4
+ Summary: Tools for working with MatPES.
5
+ Author-email: Pymatgen Development Team <ongsp@ucsd.edu>
6
+ Maintainer-email: Shyue Ping Ong <ongsp@ucsd.edu>
7
+ License: BSD-3-Clause
8
+ Keywords: VASP,analysis,crystal,materials,science,structure,ai,ml
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Chemistry
18
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
19
+ Classifier: Topic :: Scientific/Engineering :: Physics
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: <3.13,>=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: pandas>=2
25
+ Requires-Dist: pymongo>=4.11
26
+
27
+ [![GitHub license](https://img.shields.io/github/license/materialsvirtuallab/matpes)](https://github.com/materialsvirtuallab/matpes/blob/main/LICENSE)
28
+ [![Linting](https://github.com/materialsvirtuallab/matpes/workflows/Linting/badge.svg)](https://github.com/materialsvirtuallab/matpes/workflows/Linting/badge.svg)
29
+
30
+ #### Introduction
31
+
32
+ Welcome to MatPES, a foundational potential energy surface (PES) dataset for materials. This is a collaboration between
33
+ the [Materials Virtual Lab] and the [Materials Project].
34
+
35
+ Machine learning interatomic potentials (MLIPs) have revolutionized the field of computational materials science.
36
+ MLIPs use ML to reproduce the PES (energies, forces, and stresses) of a collection of atoms, typically computed
37
+ using an ab initio method such as density functional theory (DFT).
38
+ This enables the simulation of materials at much larger length and longer time scales at near-ab initio accuracy.
39
+
40
+ One of the most exciting developments in the past few years is the emergence of universal MLIPs (uMLIPs, aka materials
41
+ foundational models), with near-complete coverage of the periodic table of elements. Examples include M3GNet,[^1]
42
+ CHGNet,[^2] MACE,[^3] to name a few. uMLIPs have broad applications, including materials discovery and the
43
+ prediction of PES-derived properties such as elastic constants, phonon dispersion, etc.
44
+
45
+ However, most current uMLIPs were trained on DFT relaxation calculations from the [Materials Project].
46
+ This dataset, referred to as `MPF` or `MPTraj` in the literature, suffer from several issues:
47
+
48
+ 1. The energies, forces, and stresses are not converged to the accuracies necessary to train a high quality MLIP.
49
+ 2. Most of the structures are near-equilibrium, with very little coverage of non-equilibrium local environments.
50
+ 3. The calculations were performed using the common Perdew-Burke-Ernzerhof (PBE) generalized gradient approximation
51
+ (GGA) functional, even though improved functionals with better performance across diverse chemistries and bonding
52
+ such as the strongly constrained and appropriately normed (SCAN) meta-GGA functional already exists.
53
+
54
+ MatPES is a continuing effort to address these limitations comprehensively.
55
+
56
+ #### Goals
57
+
58
+ The aims of MatPES are three-fold:
59
+
60
+ 1. **Accuracy.** The data in MatPES was computed using static DFT calculations with stringent converegence criteria.
61
+ Please refer to the `MatPESStaticSet` in [pymatgen] for details.
62
+ 2. **Diversity.** The structures in MatPES are robustly sampled from 300K MD simulations using the original M3GNet
63
+ uMLIP.[^1] MatPES uses a modified version of DImensionality-Reduced Encoded Clusters with sTratified (DIRECT)
64
+ sampling to ensure comprehensive coverage of structures and local environments.[^4]
65
+ 3. **Quality.** MatPES contains not only data computed using the PBE functional, but also the revised regularized SCAN
66
+ (r2SCAN) meta-GGA functional. The r2SCAN functional recovers all 17 exact constraints presently known for
67
+ meta-GGA functionals and has shown good transferable accuracy across diverse bonding and chemistries.
68
+
69
+ #### How to use MatPES
70
+
71
+ ##### Download
72
+
73
+ You can download the entire MatPES dataset at [MatPES.ai](https://matpes.ai).
74
+ (note: links are not functional until publication).
75
+
76
+ We have also provided a simple tool to extract subsets of the data, e.g., by elements or chemical system, via the
77
+ `matpes` package.
78
+
79
+ ```shell
80
+ pip install matpes
81
+ ```
82
+
83
+ Example code
84
+
85
+ ##### Exploring
86
+
87
+ The [MatPES Explorer](explorer) provides a statistical visualization of the dataset.
88
+
89
+ ##### Pre-trained uMLIPs
90
+
91
+ Together with MatPES, we have released a set of MatPES uMLIPs in various architectures (M3GNet, CHGNet, TensorNet) in
92
+ the [MatGL] package. This is by far the easiest way to get started with using MatPES.
93
+
94
+ ##### Notebooks
95
+
96
+ We have provided a series of Jupyter notebooks demonstrating how to load the MatPES dataset, train a model and perform
97
+ finetuning.
98
+
99
+ #### Citing MatPES
100
+
101
+ If you use MatPES, please cite the following work:
102
+
103
+ ```txt
104
+ Aaron Kaplan, Runze Liu, Ji Qi, Tsz Wai Ko, Bowen Deng, Gerbrand Ceder, Kristin A. Persson, Shyue Ping Ong.
105
+ A foundational potential energy surface dataset for materials. Submitted.
106
+ ```
107
+
108
+ [Materials Virtual Lab]: http://materialsvirtuallab.org
109
+ [pymatgen]: https://pymatgen.org
110
+ [Materials Project]: https://materialsproject.org
111
+ [MatGL]: https://matgl.ai
112
+
113
+ [^1]: Chen, C.; Ong, S. P. A Universal Graph Deep Learning Interatomic Potential for the Periodic Table. Nat Comput
114
+ Sci 2022, 2 (11), 718-728. DOI: [10.1038/s43588-022-00349-3](http://dx.doi.org/10.1038/s43588-022-00349-3).
115
+ [^2]: Deng, B.; Zhong, P.; Jun, K.; Riebesell, J.; Han, K.; Bartel, C. J.; Ceder, G. CHGNet as a Pretrained Universal
116
+ Neural Network Potential for Charge-Informed Atomistic Modelling. Nat Mach Intell 2023, 5 (9), 1031-1041.
117
+ DOI: [10.1038/s42256-023-00716-3](http://doi.org/10.1038/s42256-023-00716-3).
118
+ [^3]: Batatia, I.; Kovacs, D. P.; Simm, G.; Ortner, C.; Csanyi, G. MACE: Higher Order Equivariant Message Passing
119
+ Neural Networks for Fast and Accurate Force Fields. Advances in Neural Information Processing Systems 2022, 35,
120
+ 11423-11436.
121
+ [^4]: Qi, J.; Ko, T. W.; Wood, B. C.; Pham, T. A.; Ong, S. P. Robust Training of Machine Learning Interatomic
122
+ Potentials with Dimensionality Reduction and Stratified Sampling. npj Computational Materials 2024, 10 (43), 1-11.
123
+ DOI: [10.1038/s41524-024-01227-4](https//doi.org/10.1038/s41524-024-01227-4).
@@ -0,0 +1,10 @@
1
+ matpes/__init__.py,sha256=VSumxkS_AXIovR4MBviK0gHouEpSXc-0jg5eQGpT8hs,141
2
+ matpes/cli.py,sha256=iNn2TVTkVVVV36i4a28X9vTagCFhDXoywzgviRcwMFA,5153
3
+ matpes/data.py,sha256=bW51Uupc18F8b7QggvGwOvphePewU3NBRr9aXgBap1k,1656
4
+ matpes/db.py,sha256=zDvmuxKFjDfGimJLxGl1i1SxyNleP5ezb-cjqqDka9k,3655
5
+ matpes-0.0.1.dist-info/LICENSE,sha256=ofleCNfv6OkRrtBLiR1RuQukYpFYX0OTkTSAZnDuKjg,1529
6
+ matpes-0.0.1.dist-info/METADATA,sha256=XlN8cXJKlsbLw2w7ecL6SV3_x8PtJJZZSQLQJ4qVO1I,6524
7
+ matpes-0.0.1.dist-info/WHEEL,sha256=jB7zZ3N9hIM9adW7qlTAyycLYW9npaWKLRzaoVcLKcM,91
8
+ matpes-0.0.1.dist-info/entry_points.txt,sha256=XHocKDf5-bJNYjfNdxQ0wS0_4WrrkvNN1PiOHrBdaWE,43
9
+ matpes-0.0.1.dist-info/top_level.txt,sha256=RNyOzjFWCo2-qB4J76OQLALulhplHC7OOZFy-uvqBhU,7
10
+ matpes-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ matpes = matpes.cli:main
@@ -0,0 +1 @@
1
+ matpes