Skip to content

Commit ca2a0d9

Browse files
authored
Ruff (#316)
* add ruff config to pyproject.toml * migrate existing linter config from setup.cfg to pyproject.toml * replace isort flake8 pyupgrade autoflake docformatter pre-commit hooks with ruff * fix auto-fixable ruff errors * remove flake8 and docformatter from pre-commit.ci skip * add codespell pre-commit args --ignore-words-list, "nd,te" since aren't read from pyproject.toml below py3.11 without tomli dep
1 parent ec02bb7 commit ca2a0d9

34 files changed

+289
-393
lines changed

.pre-commit-config.yaml

Lines changed: 7 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
ci:
22
autoupdate_schedule: quarterly
3-
skip: [mypy, flake8, docformatter]
3+
skip: [mypy]
44

55
default_stages: [commit]
66

@@ -11,29 +11,17 @@ default_install_hook_types: [pre-commit, commit-msg]
1111
exclude: ^(docs/.+|.*lock.*|jupyterlab-extension/.+|.*\.(svg|js|css))$
1212

1313
repos:
14-
- repo: https://github.com/PyCQA/isort
15-
rev: 5.12.0
14+
- repo: https://github.com/charliermarsh/ruff-pre-commit
15+
rev: v0.0.252
1616
hooks:
17-
- id: isort
17+
- id: ruff
18+
args: [--fix, --ignore, D]
1819

1920
- repo: https://github.com/psf/black
2021
rev: 23.1.0
2122
hooks:
2223
- id: black-jupyter
2324

24-
- repo: https://github.com/PyCQA/flake8
25-
rev: 6.0.0
26-
hooks:
27-
- id: flake8
28-
additional_dependencies: [flake8-bugbear]
29-
30-
- repo: https://github.com/asottile/pyupgrade
31-
rev: v3.3.1
32-
hooks:
33-
- id: pyupgrade
34-
args: [--py38-plus]
35-
exclude: ^crystal_toolkit/settings.py$
36-
3725
- repo: https://github.com/pre-commit/mirrors-mypy
3826
rev: v0.991
3927
hooks:
@@ -54,29 +42,15 @@ repos:
5442
hooks:
5543
- id: codespell
5644
stages: [commit, commit-msg]
57-
58-
- repo: https://github.com/PyCQA/autoflake
59-
rev: v2.0.1
60-
hooks:
61-
- id: autoflake
45+
args: [--ignore-words-list, "nd,te"]
6246

6347
- repo: https://github.com/nbQA-dev/nbQA
6448
rev: 1.6.1
6549
hooks:
66-
- id: nbqa-pyupgrade
67-
args: [--py38-plus]
68-
- id: nbqa-isort
69-
- id: nbqa-flake8
70-
args: [--ignore=E402]
50+
- id: nbqa-ruff
7151

7252
- repo: https://github.com/kynan/nbstripout
7353
rev: 0.6.1
7454
hooks:
7555
- id: nbstripout
7656
args: [--drop-empty-cells, --keep-output]
77-
78-
- repo: https://github.com/PyCQA/docformatter
79-
rev: v1.6.0.rc1
80-
hooks:
81-
- id: docformatter
82-
args: [--config, setup.cfg]

crystal_toolkit/apps/examples/mpcontribs/catalysis.py

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@
4545
class CatalysisApp(MPApp):
4646
@staticmethod
4747
def modify_df(dataframe: pd.DataFrame) -> list[pd.DataFrame]:
48-
"""
49-
Filter DataFrame for unary+binary materials visualization.
48+
"""Filter DataFrame for unary+binary materials visualization.
5049
5150
Args:
5251
dataframe (pd.DataFrame): the dataframe that you want to modify
@@ -93,7 +92,6 @@ def get_plot(
9392
:param user_options: Not implemented.
9493
:return: 2D plot
9594
"""
96-
9795
# Create a list of unique elements for use as axis labels
9896
element_list = df_min_E.element_tup.tolist()
9997
flat_element_list = [item for sublist in element_list for item in sublist]
@@ -108,14 +106,11 @@ def construct_grid(df, labels):
108106
el_combos = list(lookup_dict["energy"])
109107
for i in range(len(labels)):
110108
for k in range(len(labels)):
111-
if i == k:
112-
els_now = tuple(
113-
[
114-
labels[i],
115-
]
116-
)
117-
else:
118-
els_now = tuple(np.sort([labels[i], labels[k]]))
109+
els_now = (
110+
(labels[i],)
111+
if i == k
112+
else tuple(np.sort([labels[i], labels[k]]))
113+
)
119114
if els_now in el_combos:
120115
grid[i, k] = lookup_dict["energy"][els_now]
121116
random_ids = df_all_data[
@@ -261,10 +256,7 @@ def display_click_data(clickData):
261256
else:
262257
el1 = str(clickData["points"][0]["x"])
263258
el2 = str(clickData["points"][0]["y"])
264-
if el1 == el2:
265-
el_combo = el1
266-
else:
267-
el_combo = el1 + ", " + el2
259+
el_combo = el1 if el1 == el2 else el1 + ", " + el2
268260
randids = clickData["points"][0]["text"].split("-")
269261
num_calcs = str(len(randids) - 1)
270262
table = ctl.get_data_list(

crystal_toolkit/apps/main.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@
303303
panel_choices = dcc.Dropdown(
304304
options=[{"label": panel.title, "value": idx} for idx, panel in enumerate(panels)],
305305
multi=True,
306-
value=[idx for idx in range(len(panels))],
306+
value=list(range(len(panels))),
307307
id="panel-choices",
308308
)
309309

@@ -506,19 +506,18 @@ def master_update_structure(
506506
507507
Returns: an encoded Structure
508508
"""
509-
510509
if not search_mpid and not upload_data:
511510
raise PreventUpdate
512511

513512
if not dash.callback_context.triggered:
514513
raise PreventUpdate
515514

516-
if len(dash.callback_context.triggered) > 1:
517-
# triggered by both on initial load
518-
load_by = "mpid"
519-
elif (
520-
dash.callback_context.triggered[0]["prop_id"] == f"{search_component.id()}.data"
515+
if (
516+
len(dash.callback_context.triggered) > 1
517+
or dash.callback_context.triggered[0]["prop_id"]
518+
== f"{search_component.id()}.data"
521519
):
520+
# triggered by both on initial load
522521
load_by = "mpid"
523522
else:
524523
load_by = "uploaded"

crystal_toolkit/components/bandstructure.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -601,7 +601,7 @@ def get_figure(
601601
xaxis_style_dos = {}
602602
yaxis_style_dos = {}
603603

604-
y_title = dict(text="EE<sub>fermi</sub> (eV)", font=dict(size=16))
604+
y_title = dict(text="E-E<sub>fermi</sub> (eV)", font=dict(size=16))
605605
if bs:
606606
bs_traces, bs_data = BandstructureAndDosComponent.get_bandstructure_traces(
607607
bs, path_convention=path_convention, energy_window=energy_window
@@ -752,10 +752,9 @@ def get_figure(
752752
dos_domain = dos_domain or [1.0, 1.0]
753753
elif dos:
754754
bs_domain = bs_domain or [0, 0]
755-
if horizontal_dos:
756-
dos_domain = dos_domain or [0, 1.0]
757-
else:
758-
dos_domain = dos_domain or [0, 0.3]
755+
dos_domain = (
756+
dos_domain or [0, 1.0] if horizontal_dos else dos_domain or [0, 0.3]
757+
)
759758

760759
figure["layout"]["xaxis1"]["domain"] = bs_domain
761760
figure["layout"]["xaxis2"]["domain"] = dos_domain

crystal_toolkit/components/diffraction.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,8 @@ def two_theta_to_q(two_theta: float, xray_wavelength: float) -> float:
136136
def grain_to_hwhm(
137137
tau: float, two_theta: float, K: float = 0.9, wavelength: float | str = "CuKa"
138138
) -> float:
139-
"""_summary_
139+
"""Calculate the half-width half-max (alpha or gamma) for a given grain size and
140+
angle.
140141
141142
Args:
142143
tau (float): grain size in nm
@@ -197,7 +198,7 @@ def _sub_layouts(self) -> dict[str, Component]:
197198
help_str="This defines the wavelength of the incident X-ray radiation.",
198199
options=[
199200
{
200-
"label": f'{name.replace("a", "α").replace("b", "β")} ({wavelength:.3f} Å)',
201+
"label": f'{name.replace("a", "α").replace("b", "β")} ({wavelength:.3f} Å)', # noqa: RUF001
201202
"value": name,
202203
}
203204
for name, wavelength in WAVELENGTHS.items()
@@ -243,7 +244,7 @@ def _sub_layouts(self) -> dict[str, Component]:
243244
self.get_choice_input(
244245
kwarg_label="x_axis",
245246
state=state,
246-
label="Choice of 𝑥 axis",
247+
label="Choice of x axis",
247248
help_str="Can choose between 2𝜃 or Q, where Q is the magnitude of the reciprocal lattice and "
248249
"independent of radiation source.", # TODO: improve
249250
options=[
@@ -293,10 +294,7 @@ def layout(self, static_image: bool = False) -> Columns:
293294
Columns: from crystal_toolkit.helpers.layouts
294295
"""
295296
sub_layouts = self._sub_layouts
296-
if static_image:
297-
inner = sub_layouts["static_image"]
298-
else:
299-
inner = sub_layouts["graph"]
297+
inner = sub_layouts["static_image"] if static_image else sub_layouts["graph"]
300298

301299
return Columns(
302300
[
@@ -355,11 +353,8 @@ def get_figure(
355353
num_sigma = {"G": 5, "L": 12, "V": 12}[peak_profile]
356354

357355
# optimal number of points per degree determined through usage experiments
358-
if grain_size > 10:
359-
# scaled to log size to the 4th power
360-
N_density = 150 * (math.log10(grain_size) ** 4)
361-
else:
362-
N_density = 150
356+
# scaled to log size to the 4th power
357+
N_density = 150 * (math.log10(grain_size) ** 4) if grain_size > 10 else 150
363358

364359
N = int(N_density * domain) # num total points
365360

crystal_toolkit/components/localenv.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ def _get_local_order_parameters(structure_graph, n):
6464
underlying motif (e.g., CN=4, then calculate the
6565
square planar, tetrahedral, see-saw-like,
6666
rectangular see-saw-like order parameters).
67+
6768
Args:
6869
structure_graph: StructureGraph object
6970
n (int): site index.
@@ -77,7 +78,7 @@ def _get_local_order_parameters(structure_graph, n):
7778
# import, also makes sense to have this as a general NN method
7879
cn = structure_graph.get_coordination_of_site(n)
7980
if cn in [int(k_cn) for k_cn in cn_opt_params]:
80-
names = [k for k in cn_opt_params[cn]]
81+
names = list(cn_opt_params[cn])
8182
types = []
8283
params = []
8384
for name in names:
@@ -92,7 +93,7 @@ def _get_local_order_parameters(structure_graph, n):
9293
for connected_site in structure_graph.get_connected_sites(n)
9394
]
9495
lostop_vals = lostops.get_order_parameters(
95-
sites, 0, indices_neighs=[i for i in range(1, cn + 1)]
96+
sites, 0, indices_neighs=list(range(1, cn + 1))
9697
)
9798
d = {}
9899
for i, lostop in enumerate(lostop_vals):
@@ -436,7 +437,7 @@ def run_algorithm(algorithm):
436437
style={"width": "16rem"}, # TODO: remove in-line style
437438
)
438439

439-
normalize_kernel = self.get_bool_input(
440+
_normalize_kernel = self.get_bool_input(
440441
label="Normalize",
441442
kwarg_label="normalize_kernel",
442443
state=state,
@@ -797,7 +798,7 @@ def get_valences(struct):
797798

798799
# represent the local environment as a molecule
799800
mol = Molecule.from_sites(
800-
[struct[index]] + lse.neighbors_sets[index][0].neighb_sites
801+
[struct[index], *lse.neighbors_sets[index][0].neighb_sites]
801802
)
802803
mol = mol.get_centered_molecule()
803804
mg = MoleculeGraph.with_empty_graph(molecule=mol)

crystal_toolkit/components/phase_diagram.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -416,7 +416,6 @@ def ternary_plot(plot_data):
416416
417417
Returns: go.Figure
418418
"""
419-
420419
go.Scatterternary(
421420
{
422421
"mode": "markers",
@@ -656,10 +655,11 @@ def update_entries_store(rows):
656655
try:
657656
comp = Composition(row["Formula"])
658657
energy = row["Formation Energy (eV/atom)"]
659-
if row["Material ID"] is None:
660-
attribute = "Custom Entry"
661-
else:
662-
attribute = row["Material ID"]
658+
attribute = (
659+
"Custom Entry"
660+
if row["Material ID"] is None
661+
else row["Material ID"]
662+
)
663663
# create new entry object containing mpid as attribute (to combine with custom entries)
664664
entry = PDEntry(
665665
comp, float(energy) * comp.num_atoms, attribute=attribute
@@ -693,10 +693,13 @@ def create_table(chemsys, pd_time, n_clicks, pd, rows):
693693
if trigger["prop_id"] == f"{self.id()}.modified_timestamp":
694694
table_content = self.create_table_content(self.from_data(pd))
695695
return table_content
696-
elif trigger["prop_id"] == f"{self.id('editing-rows-button')}.n_clicks":
697-
if n_clicks > 0 and rows:
698-
rows.append(self.empty_row)
699-
return rows
696+
elif (
697+
trigger["prop_id"] == f"{self.id('editing-rows-button')}.n_clicks"
698+
and n_clicks > 0
699+
and rows
700+
):
701+
rows.append(self.empty_row)
702+
return rows
700703

701704
with MPRester() as mpr:
702705
entries = mpr.get_entries_in_chemsys(chemsys)

crystal_toolkit/components/phonon.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -705,7 +705,6 @@ def highlight_bz_on_hover_bs(hover_data, click_data, label_select):
705705
"""Highlight the corresponding point/edge of the Brillouin Zone when hovering the band
706706
structure plot.
707707
"""
708-
709708
# TODO: figure out what to return (CSS?) to highlight BZ edge/point
710709
return
711710

crystal_toolkit/components/pourbaix.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ def get_figure(
356356
marker={"color": "Black"},
357357
line={"color": "Black", "width": 0},
358358
mode="lines",
359-
showlegend=True if legend_entry not in include_legend else False,
359+
showlegend=legend_entry not in include_legend,
360360
)
361361
)
362362

@@ -374,10 +374,11 @@ def get_figure(
374374

375375
# stable entries are black with default color scheme,
376376
# so use white lines instead
377-
if heatmap_entry:
378-
line = {"color": "White", "width": 4}
379-
else:
380-
line = {"color": "Black", "width": 1}
377+
line = (
378+
{"color": "White", "width": 4}
379+
if heatmap_entry
380+
else {"color": "Black", "width": 1}
381+
)
381382

382383
shape = go.layout.Shape(
383384
type="path", path=path, fillcolor="rgba(0,0,0,0)", opacity=1, line=line
@@ -550,7 +551,7 @@ def _sub_layouts(self) -> dict[str, Component]:
550551
help_str="Whether to filter solid phases by stability on the compositional phase diagram. "
551552
"The practical consequence of this is that highly oxidized or reduced phases that "
552553
"might show up in experiments due to kinetic limitations on oxygen/hydrogen evolution "
553-
"wont appear in the diagram, but they are not actually “stable” (and are frequently "
554+
"won't appear in the diagram, but they are not actually “stable” (and are frequently "
554555
"overstabilized from DFT errors). Hence, including only the stable solid phases generally "
555556
"leads to the most accurate Pourbaix diagrams.",
556557
),
@@ -789,7 +790,7 @@ def make_figure(pourbaix_entries, *args) -> go.Figure:
789790
conc_dict=conc_dict,
790791
filter_solids=kwargs["filter_solids"],
791792
)
792-
self.logger.debug(
793+
self.logger.debug( # noqa: PLE1205
793794
"Generated pourbaix diagram",
794795
len(pourbaix_entries),
795796
heatmap_entry,

crystal_toolkit/components/robocrys.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,5 +49,5 @@ def run_robocrys_analysis(new_store_contents):
4949
style={"white-space": "nowrap"},
5050
)
5151
return MessageContainer(
52-
MessageBody([f"{description} ", repo_link]), kind="dark"
52+
MessageBody([f"{description} - ", repo_link]), kind="dark"
5353
)

0 commit comments

Comments
 (0)