Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

API Docs #39

Merged
merged 18 commits into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/gh-pages.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: GitHub Pages

on:
pull_request:
branches: [main]
push:
branches: [main]
workflow_dispatch:

# set permissions of GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write

jobs:
build:
uses: janosh/workflows/.github/workflows/nodejs-gh-pages.yml@main
with:
python-version: "3.11"
working-directory: site
install-cmd: npm install --force
pre-build: |
pip install '..[docs]'
python make_docs.py
34 changes: 0 additions & 34 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,49 +6,15 @@ __pycache__/
*.so

# Distribution / packaging
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
.tox/
.coverage
.cache
nosetests.xml
coverage.xml

# Translations
*.mo

# Mr Developer
.mr.developer.cfg
.project
.pydevproject

# Rope
.ropeproject

# Django stuff:
*.log
*.pot

# Sphinx documentation
docs/_build/

# Extras
*.traj
*.xml
Expand Down
24 changes: 24 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,27 @@ repos:
hooks:
- id: nbstripout
args: [--drop-empty-cells, --keep-output]

- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.0.0-alpha.6
hooks:
- id: prettier
args: [--write] # edit files in-place
additional_dependencies:
- prettier
- prettier-plugin-svelte
- svelte

- repo: https://github.com/pre-commit/mirrors-eslint
rev: v8.41.0
hooks:
- id: eslint
types: [file]
args: [--fix, --plugin, "svelte3, @typescript-eslint"]
files: \.(js|ts|svelte)$
additional_dependencies:
- eslint
- typescript
- eslint-plugin-svelte3
- "@typescript-eslint/eslint-plugin"
- "@typescript-eslint/parser"
18 changes: 10 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

A pretrained universal neural network potential for
**charge**-informed atomistic modeling
![chgnet](chgnet-logo.png)
![chgnet](https://raw.github.com/CederGroupHub/chgnet/main/site/static/chgnet-logo.png)
**C**rystal **H**amiltonian **G**raph neural **Net**work is pretrained on the GGA/GGA+U static and relaxation trajectories from Materials Project,
a comprehensive dataset consisting of 1.5 Million structures from 146k compounds spanning the whole periodic table.

Expand All @@ -25,7 +25,7 @@ DFT magnetic moments, which carry rich information about both local ionic enviro

| Notebooks | Links       | Descriptions |
| ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| [**CHGNet Basics**](https://github.com/CederGroupHub/chgnet/blob/main/examples/basics.ipynb) | [![Open in Google Colab]](https://colab.research.google.com/github/CederGroupHub/chgnet/blob/main/examples/basics.ipynb) | Examples for loading pre-trained CHGNet, predicting energy, force, stress, magmom as well as running structure optimization and MD. |
| [**CHGNet Basics**](https://github.com/CederGroupHub/chgnet/blob/main/examples/basics.ipynb) | [![Open in Google Colab]](https://colab.research.google.com/github/CederGroupHub/chgnet/blob/main/examples/basics.ipynb) | Examples for loading pre-trained CHGNet, predicting energy, force, stress, magmom as well as running structure optimization and MD. |
| [**Tuning CHGNet**](https://github.com/CederGroupHub/chgnet/blob/main/examples/fine_tuning.ipynb) | [![Open in Google Colab]](https://colab.research.google.com/github/CederGroupHub/chgnet/blob/main/examples/fine_tuning.ipynb) | Examples of fine tuning the pretrained CHGNet to your system of interest. |
| [**Visualize Relaxation**](https://github.com/CederGroupHub/chgnet/blob/main/examples/crystaltoolkit_relax_viewer.ipynb) | [![Open in Google Colab]](https://colab.research.google.com/github/CederGroupHub/chgnet/blob/main/examples/crystaltoolkit_relax_viewer.ipynb) | Crystal Toolkit that visualizes atom positions, energies and forces of a structure during CHGNet relaxation. |

Expand All @@ -39,6 +39,8 @@ You can install `chgnet` through `pip`:
pip install chgnet
```

<slot name='docs' />

## Usage

### Direct Inference (Static Calculation)
Expand Down Expand Up @@ -152,15 +154,15 @@ trainer.train(train_loader, val_loader, test_loader)

1. The energy used for training should be energy/atom if you're fine-tuning the pretrained `CHGNet`.
2. The pretrained dataset of `CHGNet` comes from GGA+U DFT with [`MaterialsProject2020Compatibility`](https://github.com/materialsproject/pymatgen/blob/v2023.2.28/pymatgen/entries/compatibility.py#L826-L1102).
The parameter for VASP is described in [`MPRelaxSet`](https://github.com/materialsproject/pymatgen/blob/v2023.2.28/pymatgen/io/vasp/sets.py#L862-L879).
If you're fine-tuning with [`MPRelaxSet`](https://github.com/materialsproject/pymatgen/blob/v2023.2.28/pymatgen/io/vasp/sets.py#L862-L879), it is recommended to apply the [`MP2020`](https://github.com/materialsproject/pymatgen/blob/v2023.2.28/pymatgen/entries/compatibility.py#L826-L1102)
compatibility to your energy labels so that they're consistent with the pretrained dataset.
The parameter for VASP is described in [`MPRelaxSet`](https://github.com/materialsproject/pymatgen/blob/v2023.2.28/pymatgen/io/vasp/sets.py#L862-L879).
If you're fine-tuning with [`MPRelaxSet`](https://github.com/materialsproject/pymatgen/blob/v2023.2.28/pymatgen/io/vasp/sets.py#L862-L879), it is recommended to apply the [`MP2020`](https://github.com/materialsproject/pymatgen/blob/v2023.2.28/pymatgen/entries/compatibility.py#L826-L1102)
compatibility to your energy labels so that they're consistent with the pretrained dataset.
3. If you're fine-tuning to functionals other than GGA, we recommend you refit the [`AtomRef`](https://github.com/CederGroupHub/chgnet/blob/main/chgnet/model/composition_model.py).
4. `CHGNet` stress is in unit GPa, and the unit conversion has already been included in
[`dataset.py`](https://github.com/CederGroupHub/chgnet/blob/main/chgnet/data/dataset.py). So `VASP` stress can be directly fed to `StructureData`
[`dataset.py`](https://github.com/CederGroupHub/chgnet/blob/main/chgnet/data/dataset.py). So `VASP` stress can be directly fed to `StructureData`
5. To save time from graph conversion step for each training, we recommend you use [`GraphData`](https://github.com/CederGroupHub/chgnet/blob/main/chgnet/data/dataset.py) defined in
[`dataset.py`](https://github.com/CederGroupHub/chgnet/blob/main/chgnet/data/dataset.py), which reads graphs directly from saved directory. To create saved graphs,
see [`examples/make_graphs.py`](https://github.com/CederGroupHub/chgnet/blob/main/examples/make_graphs.py).
[`dataset.py`](https://github.com/CederGroupHub/chgnet/blob/main/chgnet/data/dataset.py), which reads graphs directly from saved directory. To create saved graphs,
see [`examples/make_graphs.py`](https://github.com/CederGroupHub/chgnet/blob/main/examples/make_graphs.py).
6. Apple’s Metal Performance Shaders `MPS` is currently disabled until a stable version of `pytorch` for `MPS` is released.

## Reference
Expand Down
2 changes: 1 addition & 1 deletion chgnet/data/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -669,7 +669,7 @@ def get_train_val_test_loader(


def collate_graphs(batch_data: list):
"""Collate of list of (graph, target) into batch data,.
"""Collate of list of (graph, target) into batch data.

Args:
batch_data (list): list of (graph, target(dict))
Expand Down
6 changes: 2 additions & 4 deletions chgnet/model/dynamics.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,16 +71,14 @@ def __init__(

# mps is disabled before stable version of pytorch on apple mps is released
if use_device == "mps":
raise NotImplementedError("mps is not supported yet")
raise NotImplementedError("'mps' backend is not supported yet")
# elif torch.backends.mps.is_available():
# self.device = 'mps'
# Determine the device to use
self.device = use_device or ("cuda" if torch.cuda.is_available() else "cpu")

# Move the model to the specified device
if model is None:
model = CHGNet.load()
self.model = model.to(self.device)
self.model = (model or CHGNet.load()).to(self.device)
self.stress_weight = stress_weight
print(f"CHGNet will run on {self.device}")

Expand Down
28 changes: 13 additions & 15 deletions chgnet/utils/vasp_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,17 +134,17 @@ def solve_charge_by_mag(
Args:
structure: input pymatgen structure
default_ox (dict[str, float]): default oxidation state for elements.
Default = {"Li": 1, "O": -2}
ox_ranges (dict[str, dict[tuple[float, float], int]]): user defined range to
Default = dict(Li=1, O=-2)
ox_ranges (dict[str, dict[tuple[float, float], int]]): user-defined range to
convert magmoms into formal valence.
Example for Mn (Default):
{"Mn": {
(0.5, 1.5): 2,
(1.5, 2.5): 3,
(2.5, 3.5): 4,
(3.5, 4.2): 3,
(4.2, 5): 2
}}
("Mn": (
(0.5, 1.5): 2,
(1.5, 2.5): 3,
(2.5, 3.5): 4,
(3.5, 4.2): 3,
(4.2, 5): 2
))
"""
ox_list = []
solved_ox = True
Expand All @@ -153,17 +153,15 @@ def solve_charge_by_mag(
"Mn": {(0.5, 1.5): 2, (1.5, 2.5): 3, (2.5, 3.5): 4, (3.5, 4.2): 3, (4.2, 5): 2}
}

mag_key = (
"final_magmom" if "final_magmom" in structure.site_properties else "magmom"
mag = structure.site_properties.get(
"final_magmom", structure.site_properties.get("magmom")
)

mag = structure.site_properties[mag_key]

for site_i, site in enumerate(structure.sites):
for idx, site in enumerate(structure):
assigned = False
if site.species_string in ox_ranges:
for (minmag, maxmag), magox in ox_ranges[site.species_string].items():
if mag[site_i] >= minmag and mag[site_i] < maxmag:
if mag[idx] >= minmag and mag[idx] < maxmag:
ox_list.append(magox)
assigned = True
break
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ classifiers = [
test = ["pytest", "pytest-cov"]
# needed to run interactive example notebooks
crystal-toolkit = ["crystal-toolkit"]
docs = ["lazydocs"]

[project.urls]
Source = "https://github.com/CederGroupHub/chgnet"
Expand Down
28 changes: 28 additions & 0 deletions site/.eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
root: true
env:
browser: true
es2020: true
node: true
parser: '@typescript-eslint/parser'
parserOptions:
sourceType: module
ecmaVersion: latest
plugins: [svelte3, '@typescript-eslint']
extends:
- eslint:recommended
- plugin:@typescript-eslint/recommended
overrides:
- files: ['*.svelte']
processor: svelte3/svelte3
settings:
svelte3/typescript: true
rules:
indent: [error, 2, SwitchCase: 1]
'@typescript-eslint/quotes': [error, backtick, avoidEscape: true]
semi: [error, never]
linebreak-style: [error, unix]
no-console: [error, allow: [warn, error]]
no-var: error
# allow triple slash for typescript file referencing https://git.io/JCeqO
spaced-comment: [error, always, { markers: [/] }]
'@typescript-eslint/no-inferrable-types': off
7 changes: 7 additions & 0 deletions site/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# dependencies
node_modules

# production build
.svelte-kit
build
src/routes/api/*.md
43 changes: 43 additions & 0 deletions site/make_docs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""This script auto-generates markdown files from Python docstrings using lazydocs
and tweaks the output for
- prettier badges linking to source code on GitHub
- remove bold tags since they break inline code.
"""
from __future__ import annotations

import json
import os
import subprocess
from glob import glob

ROOT = os.path.dirname(os.path.dirname(__file__))
os.chdir(ROOT)
with open("site/package.json") as file:
pkg = json.load(file)
route = "site/src/routes/api"

for path in glob(f"{route}/*.md"):
os.remove(path)

subprocess.run(
f"lazydocs {pkg['name']} --output-path {route} "
f"--no-watermark --src-base-url {pkg['repository']}/blob/main",
shell=True,
)

for path in glob(f"{route}/*.md"):
with open(path) as file:
markdown = file.read()
# remove <b> tags from generated markdown as they break inline code
markdown = markdown.replace("<b>", "").replace("</b>", "")
# improve style of badges linking to source code on GitHub
markdown = markdown.replace(
'src="https://img.shields.io/badge/-source-cccccc?style=flat-square"',
'src="https://img.shields.io/badge/source-blue?style=flat" alt="source link"',
)
# remove "Global Variables" section if only contains TYPE_CHECKING
markdown = markdown.replace(
"\n**Global Variables**\n---------------\n- **TYPE_CHECKING**\n\n", ""
)
with open(path, "w") as file:
file.write(markdown)
54 changes: 54 additions & 0 deletions site/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "chgnet",
"description": "Universal neural network potential for charge-informed atomistic modeling",
"author": "Deng et al.",
"homepage": "https://CederGroupHub.github.io/chgnet",
"repository": "https://github.com/CederGroupHub/chgnet",
"license": "MIT",
"type": "module",
"bugs": "https://github.com/CederGroupHub/chgnet/issues",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"serve": "vite build && vite preview",
"changelog": "npx auto-changelog --package --output ../changelog.md --unreleased-only --hide-credit --commit-limit false"
},
"devDependencies": {
"@sveltejs/adapter-static": "^2.0.2",
"@sveltejs/kit": "^1.20.5",
"@sveltejs/vite-plugin-svelte": "^2.4.2",
"@typescript-eslint/eslint-plugin": "^5.60.1",
"@typescript-eslint/parser": "^5.60.1",
"eslint": "^8.43.0",
"eslint-plugin-svelte3": "^4.0.0",
"hastscript": "^7.2.0",
"mdsvex": "^0.11.0",
"prettier": "^2.8.8",
"prettier-plugin-svelte": "^2.10.1",
"rehype-autolink-headings": "^6.1.1",
"rehype-slug": "^5.1.0",
"svelte": "^4.0.0",
"svelte-check": "^3.4.4",
"svelte-multiselect": "^9.0.0",
"svelte-preprocess": "^5.0.4",
"svelte-toc": "^0.5.5",
"svelte-zoo": "^0.4.8",
"svelte2tsx": "^0.6.16",
"tslib": "^2.5.3",
"typescript": "^5.1.3",
"vite": "^4.3.9"
},
"prettier": {
"semi": false,
"singleQuote": true,
"overrides": [
{
"files": "*.svelte",
"options": {
"printWidth": 90
}
}
]
}
}
Loading
Loading