Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Jan 13, 2025
1 parent 2aa7bc3 commit 5808890
Show file tree
Hide file tree
Showing 30 changed files with 421 additions and 420 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -161,4 +161,4 @@ cython_debug/


# MacOS
.DS_Store
.DS_Store
1 change: 0 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,3 @@ repos:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- id: ruff-format

2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
}
}
5 changes: 4 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# https://www.sphinx-doc.org/en/master/usage/configuration.html
import os
import sys

import versioningit

sys.path.insert(0, os.path.abspath("../src"))
Expand Down Expand Up @@ -59,7 +60,9 @@
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "alabaster" # "sphinx_rtd_theme", please add corresponding package to environment.yml if you want to use it
html_theme = (
"alabaster" # "sphinx_rtd_theme", please add corresponding package to environment.yml if you want to use it
)
autosummary_generate = True

# Napoleon settings
Expand Down
473 changes: 237 additions & 236 deletions docs/ex_h5py_NXtas.py

Large diffs are not rendered by default.

281 changes: 153 additions & 128 deletions notebooks/La2Ni7_HB1A_resolution.ipynb

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions scripts/HB1A_resolution/FeSn_film_HB1A.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
p1.add_scan(fesn000p5_lscan, fmt="o")
p1.add_fit(
f1_lscan,
label=f"FWHM={f1_lscan.result.params["s1_fwhm"].value:.4f}+/-{f1_lscan.result.params["s1_fwhm"].stderr:.4f}",
label=f"FWHM={f1_lscan.result.params['s1_fwhm'].value:.4f}+/-{f1_lscan.result.params['s1_fwhm'].stderr:.4f}",
)
x = f1_lscan.result.params["s1_center"].value
components = result.eval_components(result.params, x=x)
Expand All @@ -74,7 +74,7 @@
p1_2.add_scan(fesn000p5_qscan, fmt="o")
p1_2.add_fit(
f1_qscan,
label=f"FWHM={f1_qscan.result.params["s1_fwhm"].value:.4f}+/-{f1_qscan.result.params["s1_fwhm"].stderr:.4f}",
label=f"FWHM={f1_qscan.result.params['s1_fwhm'].value:.4f}+/-{f1_qscan.result.params['s1_fwhm'].stderr:.4f}",
)
x = f1_qscan.result.params["s1_center"].value
components = result.eval_components(result.params, x=x)
Expand Down Expand Up @@ -103,7 +103,7 @@
p2.add_scan(substrate006_lscan, fmt="o")
p2.add_fit(
f2_lscan,
label=f"FWHM={f2_lscan.result.params["s1_fwhm"].value:.4f}+/-{f2_lscan.result.params["s1_fwhm"].stderr:.4f}",
label=f"FWHM={f2_lscan.result.params['s1_fwhm'].value:.4f}+/-{f2_lscan.result.params['s1_fwhm'].stderr:.4f}",
)
x = f2_lscan.result.params["s1_center"].value
components = result.eval_components(result.params, x=x)
Expand All @@ -130,7 +130,7 @@
p2_2.add_scan(substrate006_qscan, fmt="o")
p2_2.add_fit(
f2_qscan,
label=f"FWHM={f2_qscan.result.params["s1_fwhm"].value:.4f}+/-{f2_qscan.result.params["s1_fwhm"].stderr:.4f}",
label=f"FWHM={f2_qscan.result.params['s1_fwhm'].value:.4f}+/-{f2_qscan.result.params['s1_fwhm'].stderr:.4f}",
)
x = f2_qscan.result.params["s1_center"].value
components = result.eval_components(result.params, x=x)
Expand Down Expand Up @@ -169,7 +169,7 @@
p3.add_scan(fesn000p5_lscan_2, fmt="o")
p3.add_fit(
f3_lscan,
label=f"FWHM={result.params["s1_fwhm"].value:.4f}+/-{result.params["s1_fwhm"].stderr:.4f}",
label=f"FWHM={result.params['s1_fwhm'].value:.4f}+/-{result.params['s1_fwhm'].stderr:.4f}",
)
x = result.params["s1_center"].value
components = result.eval_components(result.params, x=x)
Expand Down
4 changes: 2 additions & 2 deletions scripts/HB1A_resolution/rez_HB1A.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
p4.add_fit(
hh1_fit,
x=hh1_fit.x_to_plot(),
label=f"FWHM={result.params["s1_fwhm"].value:.5f}+/-{result.params["s1_fwhm"].stderr:.5f}",
label=f"FWHM={result.params['s1_fwhm'].value:.5f}+/-{result.params['s1_fwhm'].stderr:.5f}",
)

x = hh1_fit.result.params["s1_center"].value
Expand Down Expand Up @@ -148,7 +148,7 @@
p5.add_fit(
hh1_fit_2,
x=hh1_fit.x_to_plot(),
label=f"FWHM={result.params["s1_fwhm"].value:.5f}+/-{result.params["s1_fwhm"].stderr:.5f}",
label=f"FWHM={result.params['s1_fwhm'].value:.5f}+/-{result.params['s1_fwhm'].stderr:.5f}",
)

x = hh1_fit_2.result.params["s1_center"].value
Expand Down
2 changes: 1 addition & 1 deletion scripts/Sunny_enabler/rez_loader.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ scan0042 = pdata["scan0042"]
rez_mat = read(scan0042, "rez_mat")

scan0001 = fid["data"]["IPTS32124_CG4C_exp0424"]["scan0001"]
read(scan0001["sample"], "unit_cell")
read(scan0001["sample"], "unit_cell")
1 change: 0 additions & 1 deletion scripts/Sunny_enabler/scans_rez.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
rez_r0_list = []

for i in range(len(ei_list)):

rez = tas.cooper_nathans(
ei=ei_list[i],
ef=ef_list[i],
Expand Down
2 changes: 1 addition & 1 deletion src/tavi/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

import os
import shutil

from configparser import ConfigParser
from pathlib import Path

from mantid.kernel import Logger

logger = Logger("PACKAGENAME")
Expand Down
1 change: 0 additions & 1 deletion src/tavi/data/fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,6 @@ def eval(self, pars: Parameters, x: np.ndarray) -> np.ndarray:
return self.model.eval(pars, x=x)

def fit(self, pars: Parameters, USE_ERRORBAR=True) -> ModelResult:

if USE_ERRORBAR:
result = self.model.fit(self.y, pars, x=self.x, weights=self.err)
else:
Expand Down
5 changes: 2 additions & 3 deletions src/tavi/data/nexus_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,8 @@ def spice_scan_to_nxdict(
EX_required="true",
)
for i in range(8): # CG4C horizontal focusing
nxana.add_dataset(key=f"qm{i+1}", ds=NXdataset(ds=spicelogs.get(f"qm{i+1}"), type="NX_FLOAT"))
nxana.add_dataset(key=f"xm{i+1}", ds=NXdataset(ds=spicelogs.get(f"xm{i+1}"), type="NX_FLOAT"))
nxana.add_dataset(key=f"qm{i + 1}", ds=NXdataset(ds=spicelogs.get(f"qm{i + 1}"), type="NX_FLOAT"))
nxana.add_dataset(key=f"xm{i + 1}", ds=NXdataset(ds=spicelogs.get(f"xm{i + 1}"), type="NX_FLOAT"))

if instrument_config_params is not None:
if (ana_params := instrument_config_params.get("analyzer")) is not None:
Expand Down Expand Up @@ -301,7 +301,6 @@ def spice_scan_to_nxdict(

if instrument_config_params is not None:
if (coll_params := instrument_config_params.get("collimators")) is not None:

try:
div_x = [
coll_params["h_pre_mono"],
Expand Down
1 change: 0 additions & 1 deletion src/tavi/data/scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ class Scan(object):
"""

def __init__(self, name: str, nexus_dict: NexusEntry) -> None:

self.name: str = name
self._nexus_dict: NexusEntry = nexus_dict
self.data: dict = self.get_data_columns()
Expand Down
3 changes: 0 additions & 3 deletions src/tavi/data/scan_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ def __init__(
y: np.ndarray,
norm: Optional[np.ndarray] = None,
) -> None:

# ind = np.argsort(x)
# self.x = x[ind]
# self.y = y[ind]
Expand Down Expand Up @@ -198,7 +197,6 @@ def rebin_grid(self, rebin_params: tuple):
counts = np.zeros_like(x)

for i, x0 in enumerate(self.x):

# Return the indices of the maximum values in the specified axis ignoring NaNs.
idx = np.nanargmax(x_boundary - ZERO > x0)
if idx > 0: # ignore first and last bin box
Expand Down Expand Up @@ -246,7 +244,6 @@ def rebin_grid_renorm(self, rebin_params: tuple, norm_col: Optional[np.ndarray]


class ScanData2D(object):

ZEROS = 1e-6

def __init__(
Expand Down
1 change: 0 additions & 1 deletion src/tavi/data/scan_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ def _get_data_1d(
norm_to: Optional[tuple[float, str]],
**rebin_params_dict: Optional[tuple],
) -> ScanData1D:

x_axis, y_axis = axes
x_array = np.array([])
y_array = np.array([])
Expand Down
8 changes: 4 additions & 4 deletions src/tavi/data/spice_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def read_spice_ubconf(ub_file_name: str) -> dict:
Returns:
"""
ubconf: dict[str, Any] = {}
with open(ub_file_name, 'r', encoding="utf-8") as f:
with open(ub_file_name, "r", encoding="utf-8") as f:
all_content = f.readlines()

for idx, line in enumerate(all_content):
Expand Down Expand Up @@ -129,16 +129,16 @@ def _create_spicelogs(path_to_scan_file: str) -> dict:

scan_path = os.path.abspath(path_to_scan_file)
(*folder_path, _, _) = scan_path.split("/")
ub_file_path = os.path.join('/',*folder_path,"UBConf", metadata["ubconf"])
ub_temp_file_path = os.path.join('/',*folder_path,"UBConf", "temp", metadata["ubconf"])
ub_file_path = os.path.join("/", *folder_path, "UBConf", metadata["ubconf"])
ub_temp_file_path = os.path.join("/", *folder_path, "UBConf", "temp", metadata["ubconf"])

if os.path.isfile(ub_file_path):
ub_conf_dict = {"file_path": ub_file_path}
elif os.path.isfile(ub_temp_file_path):
ub_conf_dict = {"file_path": ub_temp_file_path}
else:
ub_conf_dict = {"file_path": ""}
print(f"Cannot find UB file {metadata["ubconf"]}")
print(f"Cannot find UB file {metadata['ubconf']}")
ubconf = read_spice_ubconf(ub_file_path)
for k, v in ubconf.items():
ub_conf_dict.update({k: v})
Expand Down
2 changes: 1 addition & 1 deletion src/tavi/instrument/instrument_params/cg4c.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,4 @@
"v_post_sample": 600,
"v_post_ana": 600
}
}
}
2 changes: 1 addition & 1 deletion src/tavi/instrument/instrument_params/hb1a.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,4 @@
"v_post_sample": 600,
"v_post_ana": 600
}
}
}
2 changes: 1 addition & 1 deletion src/tavi/instrument/instrument_params/hb3.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,4 @@
"v_post_sample": 300,
"v_post_ana": 600
}
}
}
2 changes: 1 addition & 1 deletion src/tavi/instrument/instrument_params/hb3_mnte.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,4 @@
"v_post_sample": 120,
"v_post_ana": 120
}
}
}
2 changes: 1 addition & 1 deletion src/tavi/instrument/instrument_params/takin_test.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,4 @@
"v_post_sample": 30,
"v_post_ana": 30
}
}
}
3 changes: 1 addition & 2 deletions src/tavi/instrument/resolution/cooper_nathans.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,6 @@ def cooper_nathans(
hkle_list = self._generate_hkle_list(hkl_list, ei, ef)
rez_list = []
for hkl, ei, ef in hkle_list:

# q_lab = conv_mat @ hkl
# q_mod = np.linalg.norm(q_lab)
q_mod = np.linalg.norm(self.sample.b_mat @ hkl) * 2 * np.pi
Expand All @@ -223,7 +222,7 @@ def cooper_nathans(
two_theta = get_angle_from_triangle(ki, kf, q_mod) * self.goniometer._sense
except TypeError:
rez.STATUS = False
print(f"Cannot close triangle for ei={ei}, ef={ef}, hkl={np.round(hkl,3)}.")
print(f"Cannot close triangle for ei={ei}, ef={ef}, hkl={np.round(hkl, 3)}.")

rez._set_labels()
rez_list.append(rez)
Expand Down
4 changes: 1 addition & 3 deletions src/tavi/instrument/resolution/ellipsoid.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ def __init__(
sample: Xtal,
projection: Optional[tuple] = ((1, 0, 0), (0, 1, 0), (0, 0, 1)),
) -> None:

self.STATUS: bool
self.q: tuple[float, float, float]

Expand Down Expand Up @@ -278,7 +277,6 @@ def plot_ellipses(self):
fig = plt.figure(figsize=(10, 6))

for i, indices in enumerate([(0, 3), (1, 3), (2, 3), (0, 1), (1, 2), (0, 2)]):

ellipse_co = self.get_ellipse(axes=indices, PROJECTION=False)
ellipse_inco = self.get_ellipse(axes=indices, PROJECTION=True)

Expand All @@ -292,7 +290,7 @@ def plot_ellipses(self):
p.add_reso(ellipse_inco, c="k", linestyle="dashed")

ax = fig.add_subplot(
int(f"23{i+1}"),
int(f"23{i + 1}"),
axes_class=Axes,
grid_helper=p.grid_helper(ellipse_co.angle),
)
Expand Down
6 changes: 3 additions & 3 deletions src/tavi/instrument/tas.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def calculate_two_theta(
q_norm = np.sqrt(q_sq)
two_theta_radian = get_angle_from_triangle(ki, kf, q_norm)
if two_theta_radian is None:
print(f"Triangle cannot be closed at q=({qh}, {qk}, {ql}), en={ei-ef} meV.")
print(f"Triangle cannot be closed at q=({qh}, {qk}, {ql}), en={ei - ef} meV.")
return None
# elif np.rad2deg(two_theta_radian) < S2_MIN_DEG:
# pass
Expand All @@ -86,7 +86,7 @@ def calculate_ub_matrix(self, peaks: tuple[Peak, ...]):
if not isinstance(self.sample, Xtal):
raise ValueError("sample needs to be Xtal class for UB calculation.")

match (num_of_peaks := len(peaks)):
match num_of_peaks := len(peaks):
case 2:
ubconf = self._find_u_from_two_peaks(peaks)
self.sample.set_orientation(ubconf)
Expand Down Expand Up @@ -261,7 +261,7 @@ def calculate_motor_angles(self, peak: tuple, ei: float, ef: Optional[float] = N
two_theta = get_angle_from_triangle(ki, kf, q_norm)

if two_theta is None:
print(f"Triangle cannot be closed at q={hkl}, en={ei-ef} meV.")
print(f"Triangle cannot be closed at q={hkl}, en={ei - ef} meV.")
return None
if np.rad2deg(two_theta) < S2_MIN_DEG:
print(f"s2 is smaller than {S2_MIN_DEG} deg at q={hkl}.")
Expand Down
8 changes: 0 additions & 8 deletions src/tavi/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,14 @@


class FitData1D(object):

def __init__(self, x: np.ndarray, y: np.ndarray) -> None:

self.x = x
self.y = y
self.fmt: dict = {}


class ResoBar(object):

def __init__(self, pos: tuple[float, float], fwhm: float) -> None:

self.pos = pos
self.fwhm = fwhm
self.fmt: dict = {}
Expand Down Expand Up @@ -167,7 +163,6 @@ def plot(self, ax):


class Plot2D(object):

def __init__(self) -> None:
# self.ax = None
self.contour_data: list[ScanData2D] = []
Expand All @@ -186,19 +181,16 @@ def __init__(self) -> None:
self.LOG_Z = False

def add_contour(self, contour_data: ScanData2D, **kwargs):

for key, val in kwargs.items():
contour_data.fmt.update({key: val})
self.contour_data.append(contour_data)

def add_curve(self, curve_data: ScanData1D, **kwargs):

for key, val in kwargs.items():
curve_data.fmt.update({key: val})
self.curve_data.append(curve_data)

def add_reso(self, reso_data: ResoEllipse, **kwargs):

for key, val in kwargs.items():
reso_data.fmt.update({key: val})
self.reso_data.append(reso_data)
Expand Down
3 changes: 0 additions & 3 deletions tests/test_fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ def fit_data():


def test_fit_single_peak_external_model(fit_data):

s1_scan, PLOT = fit_data

f1 = Fit1D(s1_scan, fit_range=(0.5, 4.0))
Expand Down Expand Up @@ -86,7 +85,6 @@ def test_guess_initial(fit_data):


def test_fit_single_peak_internal_model(fit_data):

s1_scan, PLOT = fit_data
f1 = Fit1D(s1_scan, fit_range=(0.5, 4.0))

Expand All @@ -109,7 +107,6 @@ def test_fit_single_peak_internal_model(fit_data):


def test_fit_two_peak(fit_data):

s1_scan, PLOT = fit_data

f1 = Fit1D(s1_scan, fit_range=(0.0, 4.0), name="scan42_fit2peaks")
Expand Down
Loading

0 comments on commit 5808890

Please sign in to comment.