Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/materialsvirtuallab/matgl i…
Browse files Browse the repository at this point in the history
…nto tko
  • Loading branch information
kenko911 committed Aug 7, 2023
2 parents 53c1bb5 + 000ff48 commit 6ce9a43
Show file tree
Hide file tree
Showing 12 changed files with 82 additions and 47 deletions.
4 changes: 4 additions & 0 deletions changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ nav_order: 3

# Change Log

## 0.8.1
- Fixed bug with loading of models trained with GPUs.
- Updated default model for relaxations to be the `M3GNet-MP-2021.2.8-DIRECT-PES model`.

## 0.8.0
- Fix a bug with use of set2set in M3Gnet implementation that affected intensive models such as the formation energy
model. M3GNet model version is updated to 2 to invalidate previous models. Note that PES models are unaffected.
Expand Down
12 changes: 12 additions & 0 deletions docs/changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,18 @@ nav_order: 3

# Change Log

## 0.8.1
- Fixed bug with loading of models trained with GPUs.
- Updated default model for relaxations to be the `M3GNet-MP-2021.2.8-DIRECT-PES model`.

## 0.8.0
- Fix a bug with use of set2set in M3Gnet implementation that affected intensive models such as the formation energy
model. M3GNet model version is updated to 2 to invalidate previous models. Note that PES models are unaffected.
(@kenko911)

## 0.7.1
- Minor optimizations for memory and isolated atom training (@kenko911)

## 0.7.0
- MatGL now supports structures with isolated atoms. (@JiQi535)
- Fourier expansion layer and generalize cutoff polynomial. (@lbluque)
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ nav_order: 1
[![Linting](https://github.com/materialsvirtuallab/matgl/workflows/Linting/badge.svg)](https://github.com/materialsvirtuallab/matgl/workflows/Linting/badge.svg)
[![Testing](https://github.com/materialsvirtuallab/matgl/workflows/Testing/badge.svg)](https://github.com/materialsvirtuallab/matgl/workflows/Testing/badge.svg)
[![Downloads](https://pepy.tech/badge/matgl)](https://pepy.tech/project/matgl)
[![Coverage Status](https://coveralls.io/repos/github/materialsvirtuallab/matgl/badge.svg?branch=main)](https://coveralls.io/github/materialsvirtuallab/matgl?branch=main)
[![codecov](https://codecov.io/gh/materialsvirtuallab/matgl/branch/main/graph/badge.svg?token=3V3O79GODQ)](https://codecov.io/gh/materialsvirtuallab/matgl)

# Materials Graph Library <img src="https://github.com/materialsvirtuallab/matgl/blob/main/assets/MatGL.png?raw=true" alt="matgl" width="30%" style="float: right">
{: .no_toc }
Expand Down
8 changes: 4 additions & 4 deletions docs/matgl.ext.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ Perform calculation for an input Atoms.
Properties calculator can handle (energy, forces, …)


### _class_ matgl.ext.ase.MolecularDynamics(atoms: Atoms, potential: [Potential](matgl.apps.md#matgl.apps.pes.Potential), state_attr: torch.Tensor | None = None, ensemble: str = 'nvt', temperature: int = 300, timestep: float = 1.0, pressure: float = 6.324209121801212e-07, taut: float | None = None, taup: float | None = None, compressibility_au: float | None = None, trajectory: str | Trajectory | None = None, logfile: str | None = None, loginterval: int = 1, append_trajectory: bool = False)
### _class_ matgl.ext.ase.MolecularDynamics(atoms: Atoms, potential: [Potential](matgl.apps.md#matgl.apps.pes.Potential), state_attr: torch.Tensor | None = None, ensemble: Literal['nvt', 'npt', 'npt_berendsen'] = 'nvt', temperature: int = 300, timestep: float = 1.0, pressure: float = 6.324209121801212e-07, taut: float | None = None, taup: float | None = None, compressibility_au: float | None = None, trajectory: str | Trajectory | None = None, logfile: str | None = None, loginterval: int = 1, append_trajectory: bool = False)
Bases: `object`

Molecular dynamics class.
Expand Down Expand Up @@ -250,7 +250,7 @@ Relax an input Atoms.


### _class_ matgl.ext.ase.TrajectoryObserver(atoms: Atoms)
Bases: `object`
Bases: `Sequence`

Trajectory observer is a hook in the relaxation process that saves the
intermediate structures.
Expand All @@ -264,8 +264,8 @@ Init the Trajectory Observer from a Atoms.



#### compute_energy()
Calculate the potential energy.
#### as_pandas()
Returns: DataFrame of energies, forces, streeses, cells and atom_positions.


#### save(filename: str)
Expand Down
51 changes: 40 additions & 11 deletions docs/matgl.graph.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,32 @@ bond_vec (torch.tensor): bond distance between two atoms
bond_dist (torch.tensor): vector from src node to dst node


### matgl.graph.compute.compute_theta(edges: EdgeBatch, cosine: bool = False)
User defined dgl function to calculate bond angles from edges in a graph.


* **Parameters**


* **edges** – DGL graph edges


* **cosine** – Whether to return the cosine of the angle or the angle itself



* **Returns**

Dictionary containing bond angles and distances



* **Return type**

dict[str, torch.Tensor]



### matgl.graph.compute.compute_theta_and_phi(edges: EdgeBatch)
Calculate bond angle Theta and Phi using dgl graphs.

Expand All @@ -63,14 +89,14 @@ phi: torch.Tensor
triple_bond_lengths (torch.tensor):


### matgl.graph.compute.create_line_graph(g_batched: DGLGraph, threebody_cutoff: float)
### matgl.graph.compute.create_line_graph(g: DGLGraph, threebody_cutoff: float)
Calculate the three body indices from pair atom indices.


* **Parameters**


* **g_batched** Batched DGL graph
* **g** – DGL graph


* **threebody_cutoff** (*float*) – cutoff for three-body interactions
Expand Down Expand Up @@ -107,7 +133,7 @@ Returns:
DGLGraph object, state_attr


#### get_graph_from_processed_structure(structure, src_id, dst_id, images, lattice_matrix, Z, element_types, cart_coords)
#### get_graph_from_processed_structure(structure, src_id, dst_id, images, lattice_matrix, element_types, cart_coords)
Construct a dgl graph from processed structure and bond information.


Expand All @@ -129,9 +155,6 @@ Construct a dgl graph from processed structure and bond information.
* **lattice_matrix** – lattice information of the structure.


* **Z** – Atomic number information of all atoms in the structure.


* **element_types** – Element symbols of all atoms in the structure.


Expand All @@ -149,7 +172,7 @@ Construct a dgl graph from processed structure and bond information.
Tools to construct a dataset of DGL graphs.


### _class_ matgl.graph.data.M3GNetDataset(structures: list, energies: list, forces: list, stresses: None | list, converter: GraphConverter, threebody_cutoff: float, name='M3GNETDataset', graph_labels: list | None = None)
### _class_ matgl.graph.data.M3GNetDataset(converter: GraphConverter, threebody_cutoff: float, structures: list, energies: list | None = None, forces: list | None = None, stresses: list | None = None, labels: list | None = None, name='M3GNETDataset', label_name: str | None = None, graph_labels: list | None = None)
Bases: `DGLDataset`

Create a dataset including dgl graphs.
Expand All @@ -158,6 +181,12 @@ Create a dataset including dgl graphs.
* **Parameters**


* **converter** – dgl graph converter


* **threebody_cutoff** – cutoff for three body


* **structures** – Pymatgen structure


Expand All @@ -170,13 +199,13 @@ Create a dataset including dgl graphs.
* **stresses** – Target stresses


* **converter**dgl graph converter
* **labels**target properties


* **threebody_cutoff**cutoff for three body
* **name**name of dataset


* **name** – name of dataset
* **label_name** – name of target properties


* **graph_labels** – state attributes.
Expand Down Expand Up @@ -333,7 +362,7 @@ Dataloader for MEGNet training.



### matgl.graph.data.collate_fn(batch)
### matgl.graph.data.collate_fn(batch, include_line_graph: bool = False)
Merge a list of dgl graphs to form a batch.


Expand Down
13 changes: 8 additions & 5 deletions docs/matgl.layers.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ increasing number of roots and a given cutoff.

Details are given in: [https://arxiv.org/abs/2003.03123](https://arxiv.org/abs/2003.03123)

This is equivalent to SphericalBesselFunction class with max_l=1, i.e. only l=0 bessel fucntions), but with
This is equivalent to SphericalBesselFunction class with max_l=1, i.e. only l=0 bessel functions), but with
optional learnable frequencies.


Expand Down Expand Up @@ -1061,7 +1061,7 @@ Perform attribute (global state) update.
Readout layer for M3GNet.


### _class_ matgl.layers._readout.ReduceReadOut(op: str = 'mean', field: str = 'node_feat')
### _class_ matgl.layers._readout.ReduceReadOut(op: str = 'mean', field: Literal['node_feat', 'edge_feat'] = 'node_feat')
Bases: `Module`

Reduce atom or bond attributes into lower dimensional tensors as readout.
Expand Down Expand Up @@ -1094,7 +1094,7 @@ This could be summing up the atoms or bonds, or taking the mean, etc.

#### training(_: boo_ )

### _class_ matgl.layers._readout.Set2SetReadOut(num_steps: int, num_layers: int, field: str)
### _class_ matgl.layers._readout.Set2SetReadOut(in_feats: int, n_iters: int, n_layers: int, field: Literal['node_feat', 'edge_feat'])
Bases: `Module`

The Set2Set readout function.
Expand All @@ -1103,10 +1103,13 @@ The Set2Set readout function.
* **Parameters**


* **num_steps** (*int*) – Number of LSTM steps
* **in_feats** (*int*) – length of input feature vector


* **num_layers** (*int*) – Number of layers.
* **n_iters** (*int*) – Number of LSTM steps


* **n_layers** (*int*) – Number of layers.


* **field** (*str*) – Field of graph to perform the readout.
Expand Down
5 changes: 4 additions & 1 deletion docs/matgl.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ MatGL (Materials Graph Library) is a graph deep learning library for materials s
* [`TrajectoryObserver`](matgl.ext.md#matgl.ext.ase.TrajectoryObserver)


* [`TrajectoryObserver.compute_energy()`](matgl.ext.md#matgl.ext.ase.TrajectoryObserver.compute_energy)
* [`TrajectoryObserver.as_pandas()`](matgl.ext.md#matgl.ext.ase.TrajectoryObserver.as_pandas)


* [`TrajectoryObserver.save()`](matgl.ext.md#matgl.ext.ase.TrajectoryObserver.save)
Expand Down Expand Up @@ -145,6 +145,9 @@ MatGL (Materials Graph Library) is a graph deep learning library for materials s
* [`compute_pair_vector_and_distance()`](matgl.graph.md#matgl.graph.compute.compute_pair_vector_and_distance)


* [`compute_theta()`](matgl.graph.md#matgl.graph.compute.compute_theta)


* [`compute_theta_and_phi()`](matgl.graph.md#matgl.graph.compute.compute_theta_and_phi)


Expand Down
4 changes: 2 additions & 2 deletions docs/matgl.models.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Computational Science, 2023, 2, 718-728. DOI: 10.1038/s43588-022-00349-3.
```


### _class_ matgl.models._m3gnet.M3GNet(element_types: tuple[str], dim_node_embedding: int = 64, dim_edge_embedding: int = 64, dim_state_embedding: int | None = None, dim_state_types: int | None = None, dim_state_feats: int | None = None, max_n: int = 3, max_l: int = 3, nblocks: int = 3, rbf_type='SphericalBessel', is_intensive: bool = True, readout_type: str = 'weighted_atom', task_type: str = 'regression', cutoff: float = 5.0, threebody_cutoff: float = 4.0, units: int = 64, ntargets: int = 1, use_smooth: bool = False, use_phi: bool = False, niters_set2set: int = 3, nlayers_set2set: int = 3, field: str = 'node_feat', include_state: bool = False, activation_type: str = 'swish', \*\*kwargs)
### _class_ matgl.models._m3gnet.M3GNet(element_types: tuple[str], dim_node_embedding: int = 64, dim_edge_embedding: int = 64, dim_state_embedding: int | None = None, ntypes_state: int | None = None, dim_state_feats: int | None = None, max_n: int = 3, max_l: int = 3, nblocks: int = 3, rbf_type='SphericalBessel', is_intensive: bool = True, readout_type: str = 'weighted_atom', task_type: str = 'regression', cutoff: float = 5.0, threebody_cutoff: float = 4.0, units: int = 64, ntargets: int = 1, use_smooth: bool = False, use_phi: bool = False, niters_set2set: int = 3, nlayers_set2set: int = 3, field: Literal['node_feat', 'edge_feat'] = 'node_feat', include_state: bool = False, activation_type: str = 'swish', \*\*kwargs)
Bases: `Module`, [`IOMixIn`](matgl.utils.md#matgl.utils.io.IOMixIn)

The main M3GNet model.
Expand All @@ -47,7 +47,7 @@ The main M3GNet model.
* **dim_state_feats** (*int*) – number of state features after linear layer


* **dim_state_types** (*int*) – number of state labels
* **ntypes_state** (*int*) – number of state labels


* **max_n** (*int*) – number of radial basis expansion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,16 @@ eform = model.predict_structure(struct)
print(f"The predicted formation energy for CsCl is {float(eform):.3f} eV/atom.")
```

The predicted formation energy for CsCl is -2.272 eV/atom.


## Using the M3GNet-MP-2018.6.1-Eform model


```python
# Load the pre-trained M3GNet formation energy model
model = matgl.load_model("M3GNet-MP-2018.6.1-Eform")
eform = model.predict_structure(struct)
print(f"The predicted formation energy for CsCl is {float(eform):.3f} eV/atom.")
```

The predicted formation energy for CsCl is -2.233 eV/atom.


# MP Band gap

This is the multi-fidelity band gap model, discussed in Chen, C.; Zuo, Y.; Ye, W.; Li, X.; Ong, S. P. Learning Properties of Ordered and Disordered Materials from Multi-Fidelity Data. Nature Computational Science 2021, 1, 46–53. https://doi.org/10.1038/s43588-020-00002-x.
Expand All @@ -82,9 +77,4 @@ for i, method in ((0, "PBE"), (1, "GLLB-SC"), (2, "HSE"), (3, "SCAN")):
structure=struct, state_feats=graph_attrs
)
print(f"The predicted {method} band gap for CsCl is {float(bandgap):.3f} eV.")
```

The predicted PBE band gap for CsCl is 4.825 eV.
The predicted GLLB-SC band gap for CsCl is 8.323 eV.
The predicted HSE band gap for CsCl is 6.317 eV.
The predicted SCAN band gap for CsCl is 5.965 eV.
```
6 changes: 1 addition & 5 deletions matgl/graph/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,7 @@ def compute_theta_and_phi(edges: dgl.udf.EdgeBatch):
triple_bond_lengths (torch.tensor):
"""
angles = compute_theta(edges, cosine=True)
angles.update(
{
"phi": torch.zeros_like(angles["cos_theta"]),
}
)
angles["phi"] = torch.zeros_like(angles["cos_theta"])
return angles


Expand Down
8 changes: 3 additions & 5 deletions matgl/utils/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,9 @@ def load(cls, path: str | Path | dict, **kwargs):

_check_ver(cls, model_data)

if not torch.cuda.is_available():
state = torch.load(fpaths["state.pt"], map_location=torch.device("cpu"))
else:
state = torch.load(fpaths["state.pt"])
d = torch.load(fpaths["model.pt"])
map_location = torch.device("cpu") if not torch.cuda.is_available() else None
state = torch.load(fpaths["state.pt"], map_location=map_location)
d = torch.load(fpaths["model.pt"], map_location=map_location)

# Deserialize any args that are IOMixIn subclasses.
for k, v in d.items():
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

setup(
name="matgl",
version="0.8.0",
version="0.8.1",
author="Tsz Wai Ko, Marcel Nassar, Ji Qi, Santiago Miret, Eliott Liu, Shyue Ping Ong",
author_email="[email protected], [email protected]",
maintainer="Shyue Ping Ong",
Expand Down

0 comments on commit 6ce9a43

Please sign in to comment.