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

Switch to AEV based models #26

Merged
merged 139 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
139 commits
Select commit Hold shift + click to select a range
b6a434e
Add emle_features argument to EMLECalculator
kzinovjev Jun 20, 2024
b940100
Create and store aev_computer from ANI-2x when AEV features are used
kzinovjev Jun 20, 2024
7ffbeb5
Proof of concept replacing SOAP with AEV
kzinovjev Jun 21, 2024
e0a297e
Write 'emle-features' value to emle_settings.yaml
kzinovjev Jun 22, 2024
1061879
Keep SOAP features as default for now
kzinovjev Jun 22, 2024
c521ccd
Merge remote-tracking branch 'kzinovjev/soap-to-aev' into feature_aev
lohedges Jun 24, 2024
c664428
Blacken.
lohedges Jun 24, 2024
f62a107
Valiate 'features' kwarg and apply minor formatting tweaks.
lohedges Jun 24, 2024
7942e5e
Expose 'features' in CLI and environment variable.
lohedges Jun 24, 2024
cd630bd
Update kwarg in error message.
lohedges Jun 24, 2024
e32fa42
Handle NoneType feature kwarg from emle-server.
lohedges Jun 24, 2024
9fa510d
Formatting tweaks. [ci skip]
lohedges Jun 24, 2024
7d3e5e5
Add support for NNPOps and re-use existing AEVComputer.
lohedges Jun 24, 2024
316c70f
Switch to using autograd.grad directly.
lohedges Jun 26, 2024
6d37a76
Generalise feature naming.
lohedges Jun 26, 2024
9338c60
Fix gradient tensor use with MM embedding.
lohedges Jun 26, 2024
ca2d4da
Refactor features validation. [ci skip]
lohedges Jun 27, 2024
b3ba1fd
Extract AEVs from tuple by name. [ci skip]
lohedges Jun 27, 2024
9798741
Generalise GPRCalculator docstring.
lohedges Jun 27, 2024
1496246
Full AEV implementation with features computed in energy function.
lohedges Jun 27, 2024
59d11a0
AEVCalculator doesn't need device argument. [ci skip]
lohedges Jun 28, 2024
e5346b4
Remove comment about pt_main_thread issue. [ci skip]
lohedges Jun 28, 2024
48d83eb
Remove redundant global. [ci skip]
lohedges Jun 28, 2024
47edb09
Docstring tweaks. [ci skip]
lohedges Jun 28, 2024
82502e0
Add initial AEV based EMLE torch.nn.Module model. [ci skip]
lohedges Jun 28, 2024
9a7bc1a
Call base class constructor to ensure all attributes are initialised.
lohedges Jun 28, 2024
bb7799e
Add combined ANI2x-EMLE model. [ci skip]
lohedges Jun 28, 2024
80f3e35
Rename models module. [ci skip]
lohedges Jun 28, 2024
e16a348
Handle situations where there are no point charges.
lohedges Jun 30, 2024
74d5f38
Use same unit system as ANI2x, i.e. Angstrom and Hartree.
lohedges Jun 30, 2024
d3d3006
Formatting tweak in license header. [ci skip]
lohedges Jun 30, 2024
7868f06
Clarification in comment. [ci skip]
lohedges Jun 30, 2024
eaa9b04
Add an optimised Sire callback. [ci skip]
lohedges Jun 30, 2024
7d3457b
Allow use of NNPOps with ANI2xEMLE model. [ci skip]
lohedges Jun 30, 2024
71dfa1a
Allow model to be moved and used with existing ANI2x model. [ci skip]
lohedges Jul 1, 2024
10da04c
Named tuple isn't available for OptimizedTorchANI. [ci skip]
lohedges Jul 1, 2024
42ce48b
Make module torch scriptable. [ci skip]
lohedges Jul 1, 2024
bcfb2df
Add support for masked AEV model and torch.compile. [ci skip]
lohedges Jul 1, 2024
eee3021
Conditionally apply NNPOps optimisations. [ci skip]
lohedges Jul 1, 2024
24ecae6
Use torch.empty to create empty list of tensors. [ci skip]
lohedges Jul 1, 2024
e4e35fc
Make model dtype agnostic and support all model conversion methods.
lohedges Jul 2, 2024
208c87a
Fix .to() for self._aev_mask. [ci skip]
lohedges Jul 2, 2024
04475e9
Simplify calculation of species indices. [ci skip]
lohedges Jul 2, 2024
6b195af
Make sure all model parameters are converted to tensors. [ci skip]
lohedges Jul 2, 2024
4fcdc72
No need to store model params as a class attribute. [ci skip]
lohedges Jul 2, 2024
962a29b
Remove all redundant module attributes. [ci skip]
lohedges Jul 2, 2024
d6b7964
Remove self from model in error message. [ci skip]
lohedges Jul 2, 2024
23d8bb1
Add missing n_z tensor attribute. [ci skip]
lohedges Jul 2, 2024
ffc35c4
Remove redundant attribure. [ci skip]
lohedges Jul 2, 2024
2307d56
Apply species map updates to ANI2xEMLE forward method. [ci skip]
lohedges Jul 2, 2024
9e74f35
Call base class methods in overloads. [ci skip]
lohedges Jul 2, 2024
82bac3b
Standardise type names in docstrings. [ci skip]
lohedges Jul 3, 2024
c98fe5b
Use -1 to specify unsupported species. [ci skip]
lohedges Jul 3, 2024
ad288b5
Work around TorchANI's broken .to(torch.float32) and .float() operators.
lohedges Jul 3, 2024
189b7a8
Don't use forward_hook until it can work with TorchScript. [ci skip]
lohedges Jul 3, 2024
701acb5
Convert model to TorchScript in optimised callback. [ci skip]
lohedges Jul 3, 2024
2c92f29
Add note regarding running without optimised execution. [ci skip]
lohedges Jul 3, 2024
21e5762
Add note about forward hook and leave commented implementation.
lohedges Jul 4, 2024
8cc736a
Allow user to specify the ANI2x model index. [ci skip]
lohedges Jul 4, 2024
a95005c
Monkey-patch torchani so AEVComputer forward hook works with TorchScript
lohedges Jul 8, 2024
aee8dd3
Monkey-patch NNPOps.OptimizedTorchANI too. [ci skip]
lohedges Jul 8, 2024
d050116
Rename TorchANI monkey-patch module. [ci skip]
lohedges Jul 8, 2024
d79b1f8
Move OptimizedTorchANI model to device. [ci skip]
lohedges Jul 8, 2024
61a8040
Use register_buffer for constant model parameters. [ci skip]
lohedges Jul 15, 2024
356e306
Remove librascal and dependencies from environment file. [ci skip]
lohedges Jul 16, 2024
8f8edf0
Guard patched NNPOps class against import error. [ci skip]
lohedges Jul 17, 2024
20d42be
Add flag to specify whether NNPOps is available. [ci skip]
lohedges Jul 17, 2024
6c49db2
Energy needs to be an array/tensor. [ci skip]
lohedges Jul 29, 2024
b616925
Detach tensors and convert to NumPy arrays. [ci skip]
lohedges Jul 29, 2024
329ef51
Rename ref_soap param to ref_aev
kzinovjev Jul 30, 2024
b738405
Implement 'reference' mode for polarizabilities calculation
kzinovjev Jul 30, 2024
acb3c1a
Remove old SOAP-based model file
kzinovjev Jul 30, 2024
0575fec
Merge branch 'chemle:feature_aev' into feature_aev
kzinovjev Jul 31, 2024
5bf6abb
Merge pull request #22 from kzinovjev/feature_aev
lohedges Jul 31, 2024
2f9c1b0
Validate the alpha_mode type.
lohedges Jul 31, 2024
48ada3d
Add alpha_mode environment variable and command-line option.
lohedges Jul 31, 2024
ae072be
Blacken.
lohedges Jul 31, 2024
694ba94
Choose default model based on the specified alpha mode.
lohedges Jul 31, 2024
aa337f0
Update requirements.
lohedges Jul 31, 2024
417014e
Add alpha_model option to modules and decouple model files from repo.
lohedges Jul 31, 2024
706313b
Fix mixing of NumPy arrays and Torch Tensors.
lohedges Jul 31, 2024
18e1f49
Mask the AEV features.
lohedges Jul 31, 2024
3b6e433
Blacken.
lohedges Jul 31, 2024
fc3ac84
Add license block for vendored pygit2 example code. [ci skip]
lohedges Jul 31, 2024
8d37ff3
Handle vacuum simulations in optimised callback. [ci skip]
lohedges Jul 31, 2024
c5f9a3a
Only compute induced dipoles when needed. [ci skip]
lohedges Jul 31, 2024
81d0175
Remove redundant E_ind in module too. [ci skip]
lohedges Jul 31, 2024
7bf9bd6
Validate required keys are in model file.
lohedges Jul 31, 2024
677077f
Remove redundant MANIFEST.in file. [ci skip]
lohedges Aug 1, 2024
28c2890
Add environment file for using rascal for delta learning. [ci skip]
lohedges Aug 1, 2024
2b19eb8
Use os.path.join to create resource directory path.
lohedges Aug 1, 2024
953223d
Switch to using pip install. [ci skip]
lohedges Aug 1, 2024
c335c34
Add note about Rascal specific environment. [ci skip]
lohedges Aug 1, 2024
d3c9afe
Add section for new alpha mode option. [ci skip]
lohedges Aug 1, 2024
0e3ef12
Add NNPOps to emle-sire environment file. [ci skip]
lohedges Aug 1, 2024
d0fede5
Add Emily Engine mascot. [ci skip]
lohedges Aug 2, 2024
2d04c35
Update OpenMM section. [ci skip]
lohedges Aug 2, 2024
4d12a23
Remove redundant gitattribute. [ci skip]
lohedges Aug 2, 2024
65e774d
Link to original mascot image. [ci skip]
lohedges Aug 3, 2024
22dd887
Document reason for create_aev_calculator kwarg. [ci skip]
lohedges Aug 6, 2024
44577c5
Fix polarisability prediction. Need to square the result.
lohedges Aug 7, 2024
3d0817d
Added the MACExEMLE model
JMorado Aug 8, 2024
3c7691e
Fix typo
JMorado Aug 8, 2024
7136180
Updated MACExEMLE to optionally initialize the model without requirin…
JMorado Aug 8, 2024
6b7675f
Miscellaneous formatting
JMorado Aug 8, 2024
a136532
Addressed points raised by @lohedges
JMorado Aug 9, 2024
b546e40
Merge pull request #25 from JMorado/feature_mace
lohedges Aug 9, 2024
2801769
Refactor emle.models.
lohedges Aug 9, 2024
044305c
Rename patches module.
lohedges Aug 9, 2024
0ffc0c4
Move _get_neighbour_pairs to base class and make static.
lohedges Aug 9, 2024
8ce4be2
Add support for custom models and species.
lohedges Aug 9, 2024
b34d36e
Formatting tweaks.
lohedges Aug 9, 2024
253257d
Fix forward docstrings. [ci skip]
lohedges Aug 9, 2024
6343935
Add support for custom species to EMLECalculator.
lohedges Aug 9, 2024
db9df87
Blacken.
lohedges Aug 10, 2024
4c09678
Refactor to remove code duplication.
lohedges Aug 12, 2024
6da0239
Clarify setting of AEVs. [ci skip]
lohedges Aug 12, 2024
2184b01
Clarify pre-computed AEVs. [ci skip]
lohedges Aug 12, 2024
8e5ffc7
Fix missing _has_nnpops variable.
lohedges Aug 13, 2024
627f35a
Fix typo in passing device when loading custom MACE models.
lohedges Aug 13, 2024
15c2b89
Move _get_neigbor_pairs back to MACE module now inheritance removed.
lohedges Aug 13, 2024
3496c50
Move _get_neigbor_pairs to utility module.
lohedges Aug 13, 2024
1cb7c18
Formatting tweak. [ci skip]
lohedges Aug 13, 2024
595a725
Formatting tweaks. [ci skip]
lohedges Aug 14, 2024
6f4702f
Validate the mace_model kwarg.
lohedges Aug 14, 2024
095fac9
Miniforge now defaults to mamba. [ci skip]
lohedges Aug 14, 2024
e1835c9
Remove redundant import.
lohedges Aug 14, 2024
8f6dcae
Add basic tests for model instantiation.
lohedges Aug 14, 2024
1ee46f9
Test that each model can be converted to TorchScript.
lohedges Aug 14, 2024
ab38a0c
Need to use pip to install test dependencies.
lohedges Aug 14, 2024
e74ce0e
Need to install using conda and pip.
lohedges Aug 14, 2024
1e7281f
Test that models can calculate energies and gradients.
lohedges Aug 14, 2024
143cb72
Update test docstrings. [ci skip]
lohedges Aug 14, 2024
8be242a
Update environment files.
lohedges Aug 18, 2024
b046f9f
Pass user defined model through to ANI2xEMLE constructor.
lohedges Sep 2, 2024
70db930
Update default model names.
lohedges Oct 1, 2024
8514031
Merge branch 'main' into feature_aev
lohedges Oct 10, 2024
9038dfc
Update links for emle-sire tutorial.
lohedges Oct 10, 2024
1a1e9dc
Add section on emle.models module.
lohedges Oct 10, 2024
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
1 change: 0 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
mlmm/_version.py export-subst
emle/_version.py export-subst
6 changes: 2 additions & 4 deletions .github/workflows/main.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,9 @@ jobs:
activate-environment: emle
environment-file: environment.yaml
miniforge-version: latest
miniforge-variant: Mambaforge
use-mamba: true
#
- name: Install pytest
run: mamba install pytest
- name: Install additional test dependencies
run: conda install pytest
#
- name: Install the package
run: pip install .
Expand Down
1 change: 0 additions & 1 deletion MANIFEST.in

This file was deleted.

49 changes: 40 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
[![GitHub Actions](https://github.com/chemle/emle-engine/actions/workflows/main.yaml/badge.svg)](https://github.com/chemle/emle-engine/actions/workflows/main.yaml)
[![License: GPL v2](https://img.shields.io/badge/License-GPL_v2-blue.svg)](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html)

![Emily Engine](emily_engine.jpg)

(Mascot courtesy [Nictrain123](https://www.deviantart.com/nictrain123/art/Simply-Emily-774815887) ![CC BY 3.0](https://licensebuttons.net/l/by/3.0/80x15.png).)

A simple interface to allow electrostatic embedding of machine learning
potentials using an [ORCA](https://orcaforum.kofo.mpg.de/i-nde-x.php-)-like interface. Based on [code](https://github.com/emedio/embedding) by Kirill Zinovjev. An example [sander](htps://ambermd.org/AmberTools.h) implementation is provided. This
works by reusing the existing interface between sander and [ORCA](https://orcaforum.kofo.mpg.de/index.php), meaning
Expand Down Expand Up @@ -38,13 +42,13 @@ environment that is compatible with your CUDA driver.)
Finally, install `emle-engine`:

```sh
python setup.py install
pip install .
```

If you are developing and want an editable install, use:

```sh
python setup.py develop
pip install -e .
```

## Usage
Expand Down Expand Up @@ -156,7 +160,18 @@ regardless of where it is launched.

We also support the use [Rascal](https://github.com/lab-cosmo/librascal)
for the calculation of delta-learning corrections to the in vacuo energies and
gradients. To use, you will need to specify a model file using the `--rascal-model`
gradients. To use, you will first need to create an environment with the additional
dependencies:

```sh
conda env create -f environment_rascal.yaml
conda activate emle-rascal
```

(These are not included in the default environment as they limit the supported
Python versions.)

Then, specify a model file using the `--rascal-model`
command-line argument, or via the `EMLE_RASCAL_MODEL` environment variable.

Note that the chosen [backend](#backends) _must_ match the one used to train the model. At
Expand Down Expand Up @@ -210,6 +225,15 @@ the environment variable) or a path to a file. When using a file, this should
be formatted as a single column, with one line per QM atom. The units
are electron charge.

## Alpha mode

We support two methods for the calculation of atomic polarisabilities. The
default, `species`, uses a single volume scaling factor for each species.
Alternatively, `reference`, calculates the scaling factors using Gaussian
Process Regression (GPR) using the values learned for each reference environment.
The alpha mode can be specified using the `--alpha-mode` command-line argument,
or via the `EMLE_ALPHA_MODE` environment variable.

## Logging

Energies can be written to a file using the `--energy-file` command-line argument
Expand Down Expand Up @@ -327,9 +351,8 @@ energies.

We provide an interface between `emle-engine` and [OpenMM](https://openmm.org) via the
[Sire](https://sire.openbiosim.org/) molecular simulation framework. This allows QM/MM simulations
to be run with OpenMM using EMLE for the embedding model. This provides improved
performance and flexibility in comparison to the `sander` interface, although
the implementation should currently be treated as being _experimental_.
to be run with OpenMM using EMLE for the embedding model. This provides greatly
improved performance and flexibility in comparison to the `sander` interface.

To use, first create an `emle-sire` conda environment:

Expand All @@ -341,16 +364,24 @@ conda activate emle-sire
Next install `emle-engine` into the environment:

```sh
python setup.py install
pip install .
```

For instructions on how to use the `emle-sire` interface, see the tutorial
documentation [here](https://github.com/OpenBioSim/sire/blob/feature_emle/doc/source/tutorial/partXX/02_emle.rst).
documentation [here](https://github.com/OpenBioSim/sire/tree/devel/doc/source/tutorial/part08/02_emle.rst).

When performing end-state correction simulations using the `emle-sire` interface
there is no need to specify the `lambda_interpolate` keyword when creating an
`EMLECalculator` instance. Instead, interpolation can be enabled when creating a
`Sire` dynamics object via the same keyword. (See the [tutorial](https://github.com/OpenBioSim/sire/blob/feature_emle/doc/source/tutorial/partXX/02_emle.rst) for details.)
`Sire` dynamics object via the same keyword. (See the [tutorial](https://github.com/OpenBioSim/sire/tree/devel/doc/source/tutorial/part08/02_emle.rst) for details.)

## Torch models

The `emle.models` module provides a number of `torch` models. The base `EMLE` model
can be used to compute the EMLE energy in isolation. The combined `ANI2xEMLE`
and `MACEEMLE` models allow the computation of in vacuo and embedding energies
in one go, using the [ANI2x](https://github.com/aiqm/torchani) and [MACE](https://github.com/ACEsuit/mace) models respectively. Creating additional models is straightforward. For details of how to use the `torch` models,
see the tutorial documentation [here](https://github.com/OpenBioSim/sire/blob/feature_emle/doc/source/tutorial/part08/02_emle.rst#creating-an-emle-torch-module).

## Issues

Expand Down
28 changes: 27 additions & 1 deletion bin/emle-server
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EMLE-Engine If not, see <http://www.gnu.org/licenses/>.
# along with EMLE-Engine. If not, see <http://www.gnu.org/licenses/>.
#####################################################################

import argparse
Expand Down Expand Up @@ -58,7 +58,12 @@ try:
except:
port = None
model = os.getenv("EMLE_MODEL")
try:
species = [int(x) for x in os.getenv("EMLE_SPECIES").split(",")]
except:
species = None
method = os.getenv("EMLE_METHOD")
alpha_mode = os.getenv("EMLE_ALPHA_MODE")
mm_charges = os.getenv("EMLE_MM_CHARGES")
try:
num_clients = int(os.getenv("EMLE_NUM_CLIENTS"))
Expand All @@ -85,6 +90,10 @@ try:
qm_xyz_frequency = int(os.getenv("EMLE_QM_XYZ_FREQUENCY"))
except:
qm_xyz_frequency = 0
try:
ani2x_model_index = int(os.getenv("EMLE_ANI2X_MODEL_INDEX"))
except:
ani2x_model_index = None
rascal_model = os.getenv("EMLE_RASCAL_MODEL")
parm7 = os.getenv("EMLE_PARM7")
try:
Expand Down Expand Up @@ -124,7 +133,9 @@ env = {
"host": host,
"port": port,
"model": model,
"species": species,
"method": method,
"alpha_mode": alpha_mode,
"mm_charges": mm_charges,
"num_clients": num_clients,
"backend": backend,
Expand All @@ -136,6 +147,7 @@ env = {
"deepmd_deviation_threshold": deepmd_deviation_threshold,
"qm_xyz_file": qm_xyz_file,
"qm_xyz_frequency": qm_xyz_frequency,
"ani2x_model_index": ani2x_model_index,
"rascal_model": rascal_model,
"lambda_interpolate": lambda_interpolate,
"interpolate_steps": interpolate_steps,
Expand Down Expand Up @@ -177,13 +189,27 @@ parser.add_argument("--port", type=str, help="the port number", required=False)
parser.add_argument(
"--model", type=str, help="path to an EMLE model file", required=False
)
parser.add_argument(
"--species",
type=str,
nargs="*",
help="the species supported by the model",
required=False,
)
parser.add_argument(
"--method",
type=str,
help="the embedding method to use",
choices=["electrostatic", "mechanical", "nonpol", "mm"],
required=False,
)
parser.add_argument(
"--alpha-mode",
type=str,
help="the alpha mode to use for the embedding method",
choices=["species", "reference"],
required=False,
)
parser.add_argument(
"--mm-charges",
type=str,
Expand Down
2 changes: 1 addition & 1 deletion bin/orca
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EMLE-Engine If not, see <http://www.gnu.org/licenses/>.
# along with EMLE-Engine. If not, see <http://www.gnu.org/licenses/>.
#####################################################################

import os
Expand Down
Binary file added emily_engine.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion emle/_sander_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EMLE-Engine If not, see <http://www.gnu.org/licenses/>.
# along with EMLE-Engine. If not, see <http://www.gnu.org/licenses/>.
#####################################################################

"""ASE sander calculator implementation."""
Expand Down
2 changes: 1 addition & 1 deletion emle/_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EMLE-Engine If not, see <http://www.gnu.org/licenses/>.
# along with EMLE-Engine. If not, see <http://www.gnu.org/licenses/>.
#####################################################################

"""Simple TCP socket-server implementation."""
Expand Down
128 changes: 128 additions & 0 deletions emle/_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
#######################################################################
# EMLE-Engine: https://github.com/chemle/emle-engine
#
# Copyright: 2023-2024
#
# Authors: Lester Hedges <lester.hedges@gmail.com>
# Kirill Zinovjev <kzinovjev@gmail.com>
#
# EMLE-Engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# EMLE-Engine is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EMLE-Engine. If not, see <http://www.gnu.org/licenses/>.
#####################################################################

"""EMLE utilities."""

__author__ = "Lester Hedges"
__email__ = "lester.hedges@gmail.com"


def _fetch_resources():
"""Fetch resources required for EMLE."""

import os as _os
import pygit2 as _pygit2

# Create the name for the expected resources directory.
resource_dir = _os.path.join(
_os.path.dirname(_os.path.abspath(__file__)), "resources"
)

# Check if the resources directory exists.
if not _os.path.exists(resource_dir):
# If it doesn't, clone the resources repository.
print("Downloading EMLE resources...")
_pygit2.clone_repository(
"https://github.com/chemle/emle-models.git", resource_dir
)
else:
# If it does, open the repository and pull the latest changes.
repo = _pygit2.Repository(resource_dir)
_pull(repo)


# The MIT License (MIT)

# Copyright (c) 2015 Michael Boselowitz

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


def _pull(repo, remote_name="origin", branch="main"):
"""
Pull the latest changes from the remote repository.

Taken from:
https://github.com/MichaelBoselowitz/pygit2-examples/blob/master/examples.py
"""

import pygit2 as _pygit2

for remote in repo.remotes:
if remote.name == remote_name:
remote.fetch()
remote_master_id = repo.lookup_reference(
"refs/remotes/origin/%s" % (branch)
).target
merge_result, _ = repo.merge_analysis(remote_master_id)
# Up to date, do nothing
if merge_result & _pygit2.GIT_MERGE_ANALYSIS_UP_TO_DATE:
return
# We can just fastforward
elif merge_result & _pygit2.GIT_MERGE_ANALYSIS_FASTFORWARD:
print("Updating EMLE resources...")
repo.checkout_tree(repo.get(remote_master_id))
try:
master_ref = repo.lookup_reference("refs/heads/%s" % (branch))
master_ref.set_target(remote_master_id)
except KeyError:
repo.create_branch(branch, repo.get(remote_master_id))
repo.head.set_target(remote_master_id)
elif merge_result & _pygit2.GIT_MERGE_ANALYSIS_NORMAL:
print("Updating EMLE resources...")
repo.merge(remote_master_id)

if repo.index.conflicts is not None:
for conflict in repo.index.conflicts:
print("Conflicts found in:", conflict[0].path)
raise AssertionError("Conflicts!")

user = repo.default_signature
tree = repo.index.write_tree()
commit = repo.create_commit(
"HEAD",
user,
user,
"Merge!",
tree,
[repo.head.target, remote_master_id],
)
# We need to do this or git CLI will think we are still merging.
repo.state_cleanup()
else:
raise AssertionError("Unknown merge analysis result")
Loading
Loading