Skip to content

Commit

Permalink
Adding Pre-commit and Ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
AndresOrtegaGuerrero committed Sep 20, 2024
1 parent b042578 commit cebd34d
Show file tree
Hide file tree
Showing 36 changed files with 430 additions and 1,181 deletions.
27 changes: 27 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: CI

on: [push, pull_request]

jobs:

pre-commit:
runs-on: ubuntu-latest

steps:
# Checkout the repository
- name: Checkout code
uses: actions/checkout@v3

# Set up Python environment
- name: Set up Python 3.10
uses: actions/setup-python@v4
with:
python-version: '3.10'

# Install pre-commit
- name: Install pre-commit
run: pip install pre-commit

# Run pre-commit on all files
- name: Run pre-commit
run: pre-commit run --all-files
11 changes: 8 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ repos:
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/psf/black
rev: 24.4.2

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.1
hooks:
- id: black
- id: ruff
types_or: [python, pyi, jupyter]
args: [--fix]
- id: ruff-format
types_or: [python, pyi, jupyter]
2 changes: 1 addition & 1 deletion LICENSE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of

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.
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.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Plugin to compute vibrational properties of materials via the aiida-vibroscopy A
Once cloned the repository, `cd` into it and:

```shell
pip install -e
pip install -e
```

If you want to easily set up phonopy, use the CLI of this package (inspect it via `aiidalab-qe-vibroscopy --help`):
Expand Down
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ dependencies = [
"kaleido",
]

[tool.ruff.lint]
ignore = ["E501", "E402", "TRY003", "RUF012", "N806"]

[project.urls]
Source = "https://github.com/mikibonacci/aiidalab-qe-vibroscopy"

Expand All @@ -37,4 +40,4 @@ Source = "https://github.com/mikibonacci/aiidalab-qe-vibroscopy"
"vibronic" = "aiidalab_qe_vibroscopy.app:property"

[project.scripts]
"aiidalab-qe-vibroscopy" = "aiidalab_qe_vibroscopy.__main__:cli"
"aiidalab-qe-vibroscopy" = "aiidalab_qe_vibroscopy.__main__:cli"
2 changes: 1 addition & 1 deletion src/aiidalab_qe_vibroscopy/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
"""AiiDAlab Qe plugin for vibrational spectoscopy."""
"""AiiDAlab Qe plugin for vibrational spectoscopy."""
15 changes: 9 additions & 6 deletions src/aiidalab_qe_vibroscopy/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
So we only setup in AiiDA.
"""


@click.group()
def cli():
pass

@cli.command(
help="Setup phonopy@localhost in the current AiiDA database."
)

@cli.command(help="Setup phonopy@localhost in the current AiiDA database.")
def setup_phonopy():
load_profile()
try:
Expand All @@ -27,10 +27,12 @@ def setup_phonopy():
# Use shutil.which to find the path of the phonopy executable
phonopy_path = shutil.which("phonopy")
if not phonopy_path:
raise FileNotFoundError("Phonopy code is not found in PATH. \
raise FileNotFoundError(
"Phonopy code is not found in PATH. \
You should update your PATH. If you have not phonopy in , \
your environment, install the code via \
`pip install phonopy --user`.")
`pip install phonopy --user`."
)
# Construct the command as a list of arguments
command = [
"verdi",
Expand All @@ -53,5 +55,6 @@ def setup_phonopy():
else:
print("Code phonopy@localhost is already installed! Nothing to do here.")


if __name__ == "__main__":
cli()
cli()
15 changes: 9 additions & 6 deletions src/aiidalab_qe_vibroscopy/app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
from aiidalab_qe_vibroscopy.app.result import Result
from aiidalab_qe.common.panel import OutlinePanel

from aiidalab_qe.common.widgets import QEAppComputationalResourcesWidget, PwCodeResourceSetupWidget
from aiidalab_qe.common.widgets import (
QEAppComputationalResourcesWidget,
PwCodeResourceSetupWidget,
)


class Outline(OutlinePanel):
Expand All @@ -12,28 +15,28 @@ class Outline(OutlinePanel):


PhononWorkChainPwCode = PwCodeResourceSetupWidget(
description="pw.x for phonons", #code for the PhononWorkChain workflow",
description="pw.x for phonons", # code for the PhononWorkChain workflow",
default_calc_job_plugin="quantumespresso.pw",
)

# The finite electric field does not support npools (does not work with npools>1), so we just set it as QEAppComputationalResourcesWidget
DielectricWorkChainPwCode = QEAppComputationalResourcesWidget(
description="pw.x for dielectric", #code for the DielectricWorChain workflow",
description="pw.x for dielectric", # code for the DielectricWorChain workflow",
default_calc_job_plugin="quantumespresso.pw",
)

PhonopyCalculationCode = QEAppComputationalResourcesWidget(
description="phonopy", # code for the PhonopyCalculation calcjob",
description="phonopy", # code for the PhonopyCalculation calcjob",
default_calc_job_plugin="phonopy.phonopy",
)

property = {
"outline": Outline,
"code": {
"phonon":PhononWorkChainPwCode,
"phonon": PhononWorkChainPwCode,
"dielectric": DielectricWorkChainPwCode,
"phonopy": PhonopyCalculationCode,
},
},
"setting": Setting,
"workchain": workchain_and_builder,
"result": Result,
Expand Down
87 changes: 31 additions & 56 deletions src/aiidalab_qe_vibroscopy/app/result.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
"""Bands results view widgets
"""Bands results view widgets"""

"""
from __future__ import annotations


from aiidalab_qe.common.panel import ResultPanel
from aiidalab_qe.common.bandpdoswidget import BandPdosPlotly

from IPython.display import display
import numpy as np

from ..utils.raman.result import export_iramanworkchain_data
Expand All @@ -23,21 +22,6 @@

from ..utils.raman.result import SpectrumPlotWidget, ActiveModesWidget

def create_html_table(matrix):
"""
Create an HTML table representation of a 3x3 matrix.
:param matrix: List of lists representing a 3x3 matrix
:return: HTML table string
"""
html = '<table border="1" style="border-collapse: collapse;">'
for row in matrix:
html += '<tr>'
for cell in row:
html += f'<td style="padding: 5px; text-align: center;">{cell}</td>'
html += '</tr>'
html += '</table>'
return html

class PhononBandPdosPlotly(BandPdosPlotly):
def __init__(self, bands_data=None, pdos_data=None):
Expand Down Expand Up @@ -92,7 +76,6 @@ class Result(ResultPanel):
children_result_widget = ()

def _update_view(self):

children_result_widget = ()
tab_titles = [] # this is needed to name the sub panels

Expand All @@ -102,15 +85,14 @@ def _update_view(self):
dielectric_data = export_dielectric_data(self.node)

if phonon_data:

phonon_children = ()
if phonon_data["bands"] or phonon_data["pdos"]:
_bands_plot_view_class = PhononBandPdosPlotly(
bands_data=phonon_data["bands"][0],
pdos_data=phonon_data["pdos"][0],
)

# the data (bands and pdos) are the first element of the lists phonon_data["bands"] and phonon_data["pdos"]!
# the data (bands and pdos) are the first element of the lists phonon_data["bands"] and phonon_data["pdos"]!
downloadBandsPdos_widget = DownloadBandsPdosWidget(
data=phonon_data,
)
Expand All @@ -120,10 +102,12 @@ def _update_view(self):

phonon_children += (
_bands_plot_view_class.bandspdosfigure,
ipw.HBox(children=[
downloadBandsPdos_widget,
downloadYamlHdf5_widget,
]),
ipw.HBox(
children=[
downloadBandsPdos_widget,
downloadYamlHdf5_widget,
]
),
)

if phonon_data["thermo"]:
Expand Down Expand Up @@ -157,9 +141,8 @@ def _update_view(self):
g.add_scatter(x=T, y=E, name=f"Entropy ({E_units})")
g.add_scatter(x=T, y=Cv, name=f"Specific Heat-V=const ({Cv_units})")

downloadThermo_widget = DownloadThermoWidget(
T,F,E,Cv)

downloadThermo_widget = DownloadThermoWidget(T, F, E, Cv)

phonon_children += (
g,
downloadThermo_widget,
Expand All @@ -179,16 +162,14 @@ def _update_view(self):
if ins_data:
intensity_maps = EuphonicSuperWidget(fc=ins_data["fc"])
children_result_widget += (intensity_maps,)
tab_titles.append(f"Inelastic Neutrons")
tab_titles.append("Inelastic Neutrons")

if spectra_data:

# Here we should provide the possibility to have both IR and Raman,
# as the new logic can provide both at the same time.
# We are gonna use the same widget, providing the correct spectrum_type: "Raman" or "Ir".
children_spectra = ()
for spectrum, data in spectra_data.items():

if not data:
continue

Expand Down Expand Up @@ -223,29 +204,23 @@ def _update_view(self):
),
),
)
tab_titles.append(f"Raman/IR spectra")

#create and VBox
my_VBox = ipw.VBox(children=children_spectra, layout=ipw.Layout(width="100%"))
tab_titles.append("Raman/IR spectra")

if dielectric_data:

dielectric_results = DielectricResults(dielectric_data)
children_result_widget += (dielectric_results,)
tab_titles.append("Dielectric properties")



self.result_tabs = ipw.Tab(children=children_result_widget)

for title_index in range(len(tab_titles)):
self.result_tabs.set_title(title_index, tab_titles[title_index])

self.children = [self.result_tabs]


class DownloadBandsPdosWidget(ipw.HBox):
def __init__(self, data, **kwargs):

self.download_button = ipw.Button(
description="Download phonon bands and pdos data",
icon="pencil",
Expand All @@ -268,6 +243,7 @@ def download_data(self, _=None):
import json
from monty.json import jsanitize
import base64

file_name_bands = "phonon_bands_data.json"
file_name_pdos = "phonon_dos_data.json"
if self.bands_data[0]:
Expand Down Expand Up @@ -298,16 +274,13 @@ def _download(payload, filename):
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
""".format(
payload=payload, filename=filename
)
""".format(payload=payload, filename=filename)
)
display(javas)

class DownloadThermoWidget(ipw.HBox):

def __init__(self, T,F,E,Cv, **kwargs):


class DownloadThermoWidget(ipw.HBox):
def __init__(self, T, F, E, Cv, **kwargs):
self.download_button = ipw.Button(
description="Download thermal properties data",
icon="pencil",
Expand All @@ -316,7 +289,7 @@ def __init__(self, T,F,E,Cv, **kwargs):
layout=ipw.Layout(width="auto"),
)
self.download_button.on_click(self.download_data)

self.temperature = T
self.free_E = F
self.entropy = E
Expand All @@ -331,14 +304,19 @@ def __init__(self, T,F,E,Cv, **kwargs):
def download_data(self, _=None):
"""Function to download the phonon data."""
import json
from monty.json import jsanitize
import base64

file_name = "phonon_thermo_data.json"
data_export = {}
for key, value in zip(
["Temperature (K)","Helmoltz Free Energy (kJ/mol)",
"Entropy (J/K/mol)","Specific Heat-V=const (J/K/mol)"],
[self.temperature, self.free_E,self.entropy, self.Cv]):
[
"Temperature (K)",
"Helmoltz Free Energy (kJ/mol)",
"Entropy (J/K/mol)",
"Specific Heat-V=const (J/K/mol)",
],
[self.temperature, self.free_E, self.entropy, self.Cv],
):
if isinstance(value, np.ndarray):
data_export[key] = value.tolist()
else:
Expand All @@ -347,7 +325,6 @@ def download_data(self, _=None):
json_str = json.dumps(data_export)
b64_str = base64.b64encode(json_str.encode()).decode()
self._download(payload=b64_str, filename=file_name)


@staticmethod
def _download(payload, filename):
Expand All @@ -361,8 +338,6 @@ def _download(payload, filename):
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
""".format(
payload=payload, filename=filename
)
""".format(payload=payload, filename=filename)
)
display(javas)
display(javas)
Loading

0 comments on commit cebd34d

Please sign in to comment.