Repository: Quantum-Accelerators/quacc
Pull request #1762 (2024-02-26 15:10:33)

Common flow for elastic constants calculations
## Summary of Changes

I have implemented a common recipe to generate and calculate properties of deformed structures to obtain elastic constants.
I have also implemented and tested this flow for the EMT calculator. The code is heavily inspired by the slabs flow. 

### Checklist

- [x] I have read the ["Guidelines" section](https://quantum-accelerators.github.io/quacc/dev/contributing.html#guidelines) of the contributing guide. Don't lie! 😉
- [x] My PR is on a custom branch and is _not_ named `main`.
- [x] I have used `black`, `isort`, and `ruff` as described in the [style guide](https://quantum-accelerators.github.io/quacc/dev/contributing.html#style).
- [x] I have added relevant, comprehensive [unit tests](https://quantum-accelerators.github.io/quacc/dev/contributing.html#unit-tests).


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
	- Added a new recipe "EMT Bulk to Deformations" to the user documentation.
	- Introduced utility functions for generating deformed structures from bulk atoms.
	- Introduced a common elastic constants workflow for generating and relaxing deformed structures, with optional static calculations.
- **Documentation**
	- Expanded the recipes list in the user documentation.
- **Tests**
	- Added tests for validating the functionality of creating deformations from a bulk atomic structure.
	- Introduced a test for elastic jobs using the EMT potential on a bulk copper structure.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

buildbot-princeton: Can one of the admins verify this patch?
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/Quantum-Accelerators/quacc/pull/1762?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Quantum-Accelerators) Report
Attention: Patch coverage is `97.22222%` with `1 lines` in your changes are missing coverage. Please review.
> Project coverage is 99.38%. Comparing base [(`69a0b82`)](https://app.codecov.io/gh/Quantum-Accelerators/quacc/commit/69a0b82c97ab1ecf42236c65adb1108bc6e9ef2a?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Quantum-Accelerators) to head [(`d41ae83`)](https://app.codecov.io/gh/Quantum-Accelerators/quacc/pull/1762?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Quantum-Accelerators).
> Report is 2 commits behind head on main.

| [Files](https://app.codecov.io/gh/Quantum-Accelerators/quacc/pull/1762?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Quantum-Accelerators) | Patch % | Lines |
|---|---|---|
| [src/quacc/recipes/common/elastic.py](https://app.codecov.io/gh/Quantum-Accelerators/quacc/pull/1762?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Quantum-Accelerators#diff-c3JjL3F1YWNjL3JlY2lwZXMvY29tbW9uL2VsYXN0aWMucHk=) | 93.33% | [1 Missing :warning: ](https://app.codecov.io/gh/Quantum-Accelerators/quacc/pull/1762?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Quantum-Accelerators) |

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##             main    #1762      +/-   ##
==========================================
- Coverage   99.40%   99.38%   -0.03%     
==========================================
  Files          76       79       +3     
  Lines        3042     3078      +36     
==========================================
+ Hits         3024     3059      +35     
- Misses         18       19       +1     
```



</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/Quantum-Accelerators/quacc/pull/1762?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Quantum-Accelerators).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Quantum-Accelerators).

Nekkrad: > Thanks, @Nekkrad! This looks great. Just a few minor comments from me.
> 
> Not for this PR, but just for your own reference, you may find the code in [this module](https://github.com/materialsvirtuallab/matcalc/blob/main/matcalc/elasticity.py) in `matcalc` helpful for the post-processing.

This is something I wanted to ask, should we include some of those post-processing into the result schema or do we leave the post-processing to the user?
Andrew-S-Rosen: > > Thanks, @Nekkrad! This looks great. Just a few minor comments from me.
> > Not for this PR, but just for your own reference, you may find the code in [this module](https://github.com/materialsvirtuallab/matcalc/blob/main/matcalc/elasticity.py) in `matcalc` helpful for the post-processing.
> 
> This is something I wanted to ask, should we include some of those post-processing into the result schema or do we leave the post-processing to the user?

For initial implementations, it is helpful to do what you've done thus far --- leave it to the user. If you find yourself using this recipe a bunch though, by all means, we can/should open a PR to add a step in the `Flow` that does post-processing of the final results so that the user doesn't have to think about it at all.
coderabbitai[bot]: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- This is an auto-generated comment: summarize review in progress by coderabbit.ai -->

> [!NOTE]
> Currently processing new changes in this PR. This may take a few minutes, please wait...
> 
> <details>
> <summary>Commits</summary>
> Files that changed from the base of the PR and between 69a0b82c97ab1ecf42236c65adb1108bc6e9ef2a and c41b02da7d73b0c03eff75595a026bfa0b7043c0.
> </details>
> 
> 
> <details>
> <summary>Files selected for processing (6)</summary>
> 
> * docs/user/recipes/recipes_list.md (1 hunks)
> * src/quacc/atoms/deformation.py (1 hunks)
> * src/quacc/recipes/common/elastic.py (1 hunks)
> * src/quacc/recipes/emt/elastic.py (1 hunks)
> * tests/core/atoms/test_elastic.py (1 hunks)
> * tests/core/recipes/emt_recipes/test_emt_elastic.py (1 hunks)
> 
> </details>
> 
> 

<!-- end of auto-generated comment: summarize review in progress by coderabbit.ai --><!-- tweet_start -->

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

<details>
<summary>Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<!-- tweet_end --><!-- tips_start -->

---

<details>
<summary>Tips</summary>

### Chat

There are 3 ways to chat with CodeRabbit:

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
	- `I pushed a fix in commit <commit_id>.`
	- `Generate unit-tests for this file.`
- Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples:
	- `@coderabbitai generate unit tests for this file.`
	-	`@coderabbitai modularize this function.`
- PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
	- `@coderabbitai generate interesting stats about this repository from git and render them as a table.`
	- `@coderabbitai show all the console.log statements in this repository.`
	- `@coderabbitai read src/utils.ts and generate unit tests.`
	- `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.`

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

### CodeRabbit Commands (invoked as PR comments)

- `@coderabbitai pause` to pause the reviews on a PR.
- `@coderabbitai resume` to resume the paused reviews.
- `@coderabbitai review` to trigger a review. This is useful when automatic reviews are disabled for the repository.
- `@coderabbitai resolve` resolve all the CodeRabbit review comments.
- `@coderabbitai help` to get help.


Additionally, you can add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed.

### CodeRabbit Configration File (`.coderabbit.yaml`)

- You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository.
- The JSON schema for the configuration file is available [here](https://coderabbit.ai/integrations/coderabbit-overrides.v2.json).
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json`

### CodeRabbit Discord Community

Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback.

</details>

<!-- tips_end -->
Andrew-S-Rosen: @Nekkrad Don't worry too much about the `coderabbitai`. I wanted to try it out and see what it did. Seems useful but perhaps too chatty....... 😅 

Patch:
diff --git a/docs/user/recipes/recipes_list.md b/docs/user/recipes/recipes_list.md
index ff2ca1e9..1ed961d7 100644
--- a/docs/user/recipes/recipes_list.md
+++ b/docs/user/recipes/recipes_list.md
@@ -25,13 +25,14 @@ The list of available quacc recipes is shown below. The "Req'd Extras" column sp
 
 <center>
 
-| Name                | Decorator        | Documentation                                      | Req'd Extras     |
-| ------------------- | ---------------- | -------------------------------------------------- | ---------------- |
-| EMT Static          | `#!Python @job`  | [quacc.recipes.emt.core.static_job][]              |                  |
-| EMT Relax           | `#!Python @job`  | [quacc.recipes.emt.core.relax_job][]               |                  |
-| EMT Bulk to Defects | `#!Python @flow` | [quacc.recipes.emt.defects.bulk_to_defects_flow][] | `quacc[defects]` |
-| EMT Bulk to Slabs   | `#!Python @flow` | [quacc.recipes.emt.slabs.bulk_to_slabs_flow][]     |                  |
-| EMT Phonons         | `#!Python @flow` | [quacc.recipes.emt.phonons.phonon_flow][]          | `quacc[phonons]` |
+| Name                      | Decorator        | Documentation                                           | Req'd Extras     |
+| ------------------------- | ---------------- | ------------------------------------------------------- | ---------------- |
+| EMT Static                | `#!Python @job`  | [quacc.recipes.emt.core.static_job][]                   |                  |
+| EMT Relax                 | `#!Python @job`  | [quacc.recipes.emt.core.relax_job][]                    |                  |
+| EMT Bulk to Defects       | `#!Python @flow` | [quacc.recipes.emt.defects.bulk_to_defects_flow][]      | `quacc[defects]` |
+| EMT Bulk to Slabs         | `#!Python @flow` | [quacc.recipes.emt.slabs.bulk_to_slabs_flow][]          |                  |
+| EMT Phonons               | `#!Python @flow` | [quacc.recipes.emt.phonons.phonon_flow][]               | `quacc[phonons]` |
+| EMT Bulk to Deformations  | `#!Python @flow` | [quacc.recipes.emt.elastic.bulk_to_deformations_flow][] |                  |
 
 </center>
 
diff --git a/src/quacc/atoms/deformation.py b/src/quacc/atoms/deformation.py
new file mode 100644
index 00000000..5e7d3963
--- /dev/null
+++ b/src/quacc/atoms/deformation.py
@@ -0,0 +1,47 @@
+"""Utility functions for dealing with deformations."""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+from ase import Atoms
+from pymatgen.analysis.elasticity.strain import DeformedStructureSet
+from pymatgen.io.ase import AseAtomsAdaptor
+
+
+def make_deformations_from_bulk(
+    atoms: Atoms,
+    norm_strains: Sequence[float] = (-0.01, -0.005, 0.005, 0.01),
+    shear_strains: Sequence[float] = (-0.06, -0.03, 0.03, 0.0),
+    symmetry: bool = False,
+) -> list[Atoms]:
+    """
+    Function to generate deformed structures from a bulk atoms object.
+
+    Parameters
+    ----------
+    atoms
+        bulk atoms
+    norm_strains
+        strain values to apply to each normal mode.
+    shear_strains
+        strain values to apply to each shear mode.
+    symmetry
+        whether or not to use symmetry reduction
+
+    Returns
+    -------
+    list[Atoms]
+        All generated deformed structures
+    """
+
+    struct = AseAtomsAdaptor.get_structure(atoms)
+
+    deformed_set = DeformedStructureSet(
+        struct,
+        norm_strains=norm_strains,
+        shear_strains=shear_strains,
+        symmetry=symmetry,
+    )
+
+    return [AseAtomsAdaptor.get_atoms(structure) for structure in deformed_set]
diff --git a/src/quacc/recipes/common/elastic.py b/src/quacc/recipes/common/elastic.py
new file mode 100644
index 00000000..33d5535c
--- /dev/null
+++ b/src/quacc/recipes/common/elastic.py
@@ -0,0 +1,64 @@
+"""Common elastic constants workflows."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from quacc import subflow
+from quacc.atoms.deformation import make_deformations_from_bulk
+
+if TYPE_CHECKING:
+    from typing import Any
+
+    from ase.atoms import Atoms
+
+    from quacc import Job
+
+
+@subflow
+def bulk_to_deformations_subflow(
+    atoms: Atoms,
+    relax_job: Job,
+    static_job: Job | None = None,
+    deform_kwargs: dict[str, Any] | None = None,
+) -> list[dict]:
+    """
+    Workflow consisting of:
+
+    1. Deformed structures generation
+
+    2. Deformed structures relaxations
+
+    3. Deformed structures statics (optional)
+
+    Parameters
+    ----------
+    atoms
+        Atoms object
+    relax_job
+        The relaxation function.
+    static_job
+        The static function.
+    deform_kwargs
+        Additional keyword arguments to pass to
+        [quacc.atoms.deformation.make_deformations_from_bulk][]
+
+    Returns
+    -------
+    list[dict]
+        List of schemas.
+    """
+    deform_kwargs = deform_kwargs or {}
+
+    deformations = make_deformations_from_bulk(atoms, **deform_kwargs)
+
+    results = []
+    for deformed in deformations:
+        result = relax_job(deformed)
+
+        if static_job is not None:
+            result = static_job(result["atoms"])
+
+        results.append(result)
+
+    return results
diff --git a/src/quacc/recipes/emt/elastic.py b/src/quacc/recipes/emt/elastic.py
new file mode 100644
index 00000000..ccfe6203
--- /dev/null
+++ b/src/quacc/recipes/emt/elastic.py
@@ -0,0 +1,75 @@
+"""Elastic constants recipes for EMT."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from quacc import flow
+from quacc.recipes.common.elastic import bulk_to_deformations_subflow
+from quacc.recipes.emt.core import relax_job, static_job
+from quacc.wflow_tools.customizers import customize_funcs
+
+if TYPE_CHECKING:
+    from typing import Any, Callable
+
+    from ase.atoms import Atoms
+
+    from quacc.schemas._aliases.ase import OptSchema, RunSchema
+
+
+@flow
+def bulk_to_deformations_flow(
+    atoms: Atoms,
+    run_static: bool = True,
+    deform_kwargs: dict[str, Any] | None = None,
+    job_params: dict[str, dict[str, Any]] | None = None,
+    job_decorators: dict[str, Callable | None] | None = None,
+) -> list[RunSchema | OptSchema]:
+    """
+    Workflow consisting of:
+
+    1. Deformed structures generation
+
+    2. Deformed structures relaxations
+        - name: "relax_job"
+        - job: [quacc.recipes.emt.core.relax_job][]
+
+    3. Deformed structures statics (optional)
+        - name: "static_job"
+        - job: [quacc.recipes.emt.core.static_job][]
+
+    Parameters
+    ----------
+    atoms
+        Atoms object
+    run_static
+        Whether to run static calculations.
+    deform_kwargs
+        Additional keyword arguments to pass to [quacc.atoms.deformation.make_deformations_from_bulk][]
+    job_params
+        Custom parameters to pass to each Job in the Flow. This is a dictionary where
+        the keys are the names of the jobs and the values are dictionaries of parameters.
+    job_decorators
+        Custom decorators to apply to each Job in the Flow. This is a dictionary where
+        the keys are the names of the jobs and the values are decorators.
+
+    Returns
+    -------
+    list[RunSchema | OptSchema]
+        [RunSchema][quacc.schemas.ase.summarize_run] or
+        [OptSchema][quacc.schemas.ase.summarize_opt_run] for each deformation.
+        See the return type-hint for the data structure.
+    """
+    relax_job_, static_job_ = customize_funcs(
+        ["relax_job", "static_job"],
+        [relax_job, static_job],
+        parameters=job_params,
+        decorators=job_decorators,
+    )
+
+    return bulk_to_deformations_subflow(
+        atoms,
+        relax_job_,
+        static_job=static_job_ if run_static else None,
+        deform_kwargs=deform_kwargs,
+    )


Test patch:
diff --git a/tests/core/atoms/test_elastic.py b/tests/core/atoms/test_elastic.py
new file mode 100644
index 00000000..eddcb319
--- /dev/null
+++ b/tests/core/atoms/test_elastic.py
@@ -0,0 +1,21 @@
+from pathlib import Path
+
+import pytest
+from ase.io import read
+from numpy.testing import assert_equal
+
+from quacc.atoms.deformation import make_deformations_from_bulk
+
+FILE_DIR = Path(__file__).parent
+
+
+def test_make_deformations_from_bulk():
+    atoms = read(FILE_DIR / "ZnTe.cif.gz")
+    atoms.info["test"] = "hi"
+    deformations = make_deformations_from_bulk(atoms)
+    assert len(deformations) == 24
+    assert deformations[0].get_volume() != pytest.approx(atoms.get_volume())
+    for deformation in deformations:
+        assert_equal(deformation.get_atomic_numbers(), [30, 30, 30, 30, 52, 52, 52, 52])
+        assert_equal(deformation.get_chemical_formula(), "Te4Zn4")
+        assert deformation.info["test"] == "hi"
diff --git a/tests/core/recipes/emt_recipes/test_emt_elastic.py b/tests/core/recipes/emt_recipes/test_emt_elastic.py
new file mode 100644
index 00000000..f003e01f
--- /dev/null
+++ b/tests/core/recipes/emt_recipes/test_emt_elastic.py
@@ -0,0 +1,30 @@
+import pytest
+from ase.build import bulk
+
+from quacc.recipes.emt.elastic import bulk_to_deformations_flow
+
+
+def test_elastic_jobs(tmp_path, monkeypatch):
+    monkeypatch.chdir(tmp_path)
+
+    atoms = bulk("Cu")
+
+    outputs = bulk_to_deformations_flow(atoms, run_static=False)
+    assert outputs[0]["atoms"].get_volume() != pytest.approx(atoms.get_volume())
+    for output in outputs:
+        assert output["parameters"]["asap_cutoff"] is False
+        assert output["name"] == "EMT Relax"
+        assert output["nelements"] == 1
+        assert output["nsites"] == 1
+        assert len(outputs) == 24
+
+    outputs = bulk_to_deformations_flow(
+        atoms, run_static=True, job_params={"static_job": {"asap_cutoff": True}}
+    )
+    assert outputs[0]["atoms"].get_volume() != pytest.approx(atoms.get_volume())
+    for output in outputs:
+        assert output["parameters"]["asap_cutoff"] is True
+        assert output["name"] == "EMT Static"
+        assert output["nelements"] == 1
+        assert output["nsites"] == 1
+        assert len(outputs) == 24