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

Add pre-commit for running black excluding database files #2

Merged
merged 2 commits into from
Oct 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
repos:
- repo: https://github.com/psf/black
# Version can be updated by running "pre-commit autoupdate"
rev: 23.10.1
hooks:
- id: black
10 changes: 6 additions & 4 deletions doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,13 @@

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = '_static/hyperspy_logo.png'
html_logo = "_static/hyperspy_logo.png"

# -- Options for sphinx_favicon extension -----------------------------------

favicons = ["hyperspy.ico", ]
favicons = [
"hyperspy.ico",
]

# Check links to API when building documentation
nitpicky = False
Expand All @@ -110,10 +112,10 @@
if Version(numpydoc.__version__) >= Version("1.6.0rc0"):
numpydoc_validation_checks = {"all", "ES01", "EX01", "GL02", "GL03", "SA01", "SS06"}

autoclass_content = 'both'
autoclass_content = "both"

autodoc_default_options = {
'show-inheritance': True,
"show-inheritance": True,
}
toc_object_entries_show_parents = "hide"

Expand Down
6 changes: 2 additions & 4 deletions examples/model_fitting/EELS_curve_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@

s.add_elements(("Mn", "O"))
s.set_microscope_parameters(
beam_energy=300,
convergence_angle=24.6,
collection_angle=13.6
)
beam_energy=300, convergence_angle=24.6, collection_angle=13.6
)

m = s.create_model(ll=ll)
m.enable_fine_structure()
Expand Down
12 changes: 6 additions & 6 deletions examples/model_fitting/plot_residual.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,28 @@
import numpy as np
import hyperspy.api as hs

#%%
# %%
# Create a signal:
data = np.arange(1000, dtype=np.int64).reshape((10, 100))
s = hs.signals.Signal1D(data)

#%%
# %%
# Add noise:
s.add_poissonian_noise(random_state=0)

#%%
# %%
# Create model:
m = s.create_model()
line = hs.model.components1D.Expression("a * x + b", name="Affine")
m.append(line)

#%%
# %%
# Fit for all navigation positions:
m.multifit()

#%%
# %%
# Plot the fitted model with residual:
m.plot(plot_residual=True)

#%%
# %%
# sphinx_gallery_thumbnail_number = 2
3 changes: 1 addition & 2 deletions exspy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

from . import components
from . import data
from . import models
Expand All @@ -11,7 +10,7 @@
"components",
"data",
"preferences",
"material"
"material",
"models",
"signals",
]
Expand Down
68 changes: 36 additions & 32 deletions exspy/_defaults_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

config_path = Path("~/.exspy").expanduser()
config_path.mkdir(parents=True, exist_ok=True)
defaults_file = Path(config_path, 'exspyrc')
defaults_file = Path(config_path, "exspyrc")

_logger = logging.getLogger(__name__)

Expand All @@ -37,52 +37,56 @@ def guess_gos_path():
# If DM is installed, use the GOS tables from the default
# installation
# location in windows
program_files = os.environ['PROGRAMFILES']
gos = 'Gatan\\DigitalMicrograph\\EELS Reference Data\\H-S GOS Tables'
program_files = os.environ["PROGRAMFILES"]
gos = "Gatan\\DigitalMicrograph\\EELS Reference Data\\H-S GOS Tables"
gos_path = Path(program_files, gos)

# Else, use the default location in the .hyperspy forlder
if not gos_path.is_dir() and 'PROGRAMFILES(X86)' in os.environ:
program_files = os.environ['PROGRAMFILES(X86)']
if not gos_path.is_dir() and "PROGRAMFILES(X86)" in os.environ:
program_files = os.environ["PROGRAMFILES(X86)"]
gos_path = Path(program_files, gos)
if not gos_path.is_dir():
gos_path = Path(config_path, 'EELS_GOS')
gos_path = Path(config_path, "EELS_GOS")
else:
gos_path = Path(config_path, 'EELS_GOS')
gos_path = Path(config_path, "EELS_GOS")
return gos_path


class EELSConfig(t.HasTraits):
eels_gos_files_path = t.Directory(
guess_gos_path(),
label='Hartree-Slater GOS directory',
desc='The GOS files are used to create the EELS edge components')
label="Hartree-Slater GOS directory",
desc="The GOS files are used to create the EELS edge components",
)


class EDSConfig(t.HasTraits):
eds_mn_ka = t.CFloat(130.,
label='Energy resolution at Mn Ka (eV)',
desc='default value for FWHM of the Mn Ka peak in eV,'
'This value is used as a first approximation'
'of the energy resolution of the detector.')
eds_mn_ka = t.CFloat(
130.0,
label="Energy resolution at Mn Ka (eV)",
desc="default value for FWHM of the Mn Ka peak in eV,"
"This value is used as a first approximation"
"of the energy resolution of the detector.",
)
eds_tilt_stage = t.CFloat(
0.,
label='Stage tilt',
desc='default value for the stage tilt in degree.')
0.0, label="Stage tilt", desc="default value for the stage tilt in degree."
)
eds_detector_azimuth = t.CFloat(
0.,
label='Azimuth angle',
desc='default value for the azimuth angle in degree. If the azimuth'
' is zero, the detector is perpendicular to the tilt axis.')
0.0,
label="Azimuth angle",
desc="default value for the azimuth angle in degree. If the azimuth"
" is zero, the detector is perpendicular to the tilt axis.",
)
eds_detector_elevation = t.CFloat(
35.,
label='Elevation angle',
desc='default value for the elevation angle in degree.')
35.0,
label="Elevation angle",
desc="default value for the elevation angle in degree.",
)


template = {
'EELS': EELSConfig(),
'EDS': EDSConfig(),
"EELS": EELSConfig(),
"EDS": EDSConfig(),
}


Expand All @@ -97,9 +101,9 @@ def config2template(template, config):
for section, traited_class in template.items():
config_dict = {}
for name, value in config.items(section):
if value == 'True':
if value == "True":
value = True
elif value == 'False':
elif value == "False":
value = False
config_dict[name] = value
traited_class.trait_set(True, **config_dict)
Expand Down Expand Up @@ -128,7 +132,7 @@ def config2template(template, config):
rewrite = True

if not defaults_file_exists or rewrite is True:
_logger.info('Writing the config file')
_logger.info("Writing the config file")
with open(defaults_file, "w") as df:
config.write(df)

Expand All @@ -144,10 +148,10 @@ class Preferences(t.HasTraits):
def save(self):
config = configparser.ConfigParser(allow_no_value=True)
template2config(template, config)
config.write(open(defaults_file, 'w'))
config.write(open(defaults_file, "w"))


preferences = Preferences(
EELS=template['EELS'],
EDS=template['EDS'],
EELS=template["EELS"],
EDS=template["EDS"],
)
2 changes: 1 addition & 1 deletion exspy/components/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"SEE",
"Vignetting",
"VolumePlasmonDrude",
]
]


def __dir__():
Expand Down
3 changes: 1 addition & 2 deletions exspy/components/eels_arctan.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@


class EELSArctan(Expression):

r"""Arctan function component for EELS (with minimum at zero).

.. math::
Expand Down Expand Up @@ -52,7 +51,7 @@ class EELSArctan(Expression):

"""

def __init__(self, A=1., k=1., x0=1., module=["numpy", "scipy"], **kwargs):
def __init__(self, A=1.0, k=1.0, x0=1.0, module=["numpy", "scipy"], **kwargs):
# To be able to still read old file versions that contain this argument
if "minimum_at_zero" in kwargs:
del kwargs["minimum_at_zero"]
Expand Down
52 changes: 30 additions & 22 deletions exspy/components/eels_cl_edge.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
# along with exSpy. If not, see <https://www.gnu.org/licenses/#GPL>.



import functools
import logging
import math
Expand Down Expand Up @@ -141,7 +140,9 @@ class EELSCLEdge(Component):
fine_structure_components : set, default ``set()``
A set containing components to model the fine structure region
of the EELS ionization edge.
""".format(_GOSH_DOI)
""".format(
_GOSH_DOI
)

_fine_structure_smoothing = 0.3
_fine_structure_coeff_free = True
Expand Down Expand Up @@ -200,11 +201,9 @@ def __init__(self, element_subshell, GOS="gosh", gos_file_path=None):
self._whitelist["fine_structure_spline_onset"] = None
self._whitelist["fine_structure_spline_active"] = None
self._whitelist["_fine_structure_coeff_free"] = None
self.effective_angle.events.value_changed.connect(
self._integrate_GOS, [])
self.effective_angle.events.value_changed.connect(self._integrate_GOS, [])
self.onset_energy.events.value_changed.connect(self._integrate_GOS, [])
self.onset_energy.events.value_changed.connect(
self._calculate_knots, [])
self.onset_energy.events.value_changed.connect(self._calculate_knots, [])
self._fine_structure_spline_onset = 0
self.events.active_changed.connect(self._set_active_fine_structure_components)

Expand Down Expand Up @@ -249,25 +248,25 @@ def fine_structure_width(self, arg):
@property
def E0(self):
return self.__E0

@E0.setter
def E0(self, arg):
self.__E0 = arg
self._calculate_effective_angle()

@property
def collection_angle(self):
return self.__collection_angle

@collection_angle.setter
def collection_angle(self, arg):
self.__collection_angle = arg
self._calculate_effective_angle()

@property
def convergence_angle(self):
return self.__convergence_angle

@convergence_angle.setter
def convergence_angle(self, arg):
self.__convergence_angle = arg
Expand Down Expand Up @@ -306,7 +305,7 @@ def fine_structure_smoothing(self, value):
if 0 <= value <= 1:
self._fine_structure_smoothing = value
self._set_fine_structure_coeff()
if self.fine_structure_active and self.model:
if self.fine_structure_active and self.model:
self.model.update_plot()
else:
raise ValueError("The value must be a number between 0 and 1")
Expand All @@ -324,7 +323,7 @@ def fine_structure_spline_onset(self, value):
if not np.allclose(value, self._fine_structure_spline_onset):
self._fine_structure_spline_onset = value
self._set_fine_structure_coeff()
if self.fine_structure_active and self.model:
if self.fine_structure_active and self.model:
self.model.update_plot()

@property
Expand All @@ -341,16 +340,22 @@ def fine_structure_spline_active(self, value):
self._fine_structure_coeff_free = self.fine_structure_coeff.free
self.fine_structure_coeff.free = False
self._fine_structure_spline_active = value
if self.fine_structure_active and self.model:
if self.fine_structure_active and self.model:
self.model.update_plot()

def _set_fine_structure_coeff(self):
if self.energy_scale is None:
return
self.fine_structure_coeff._number_of_elements = int(
round(self.fine_structure_smoothing *
(self.fine_structure_width - self.fine_structure_spline_onset) /
self.energy_scale)) + 4
self.fine_structure_coeff._number_of_elements = (
int(
round(
self.fine_structure_smoothing
* (self.fine_structure_width - self.fine_structure_spline_onset)
/ self.energy_scale
)
)
+ 4
)
self.fine_structure_coeff.bmin = None
self.fine_structure_coeff.bmax = None
self._calculate_knots()
Expand All @@ -376,10 +381,10 @@ def fix_fine_structure(self):
def free_fine_structure(self):
"""Frees the parameters of the fine structure

If there are fine structure components, only the
If there are fine structure components, only the
parameters that have been previously fixed with
``fix_fine_structure`` will be set free.

The spline parameters set free only if
``fine_structure_spline_active`` is ``True``.

Expand Down Expand Up @@ -468,7 +473,8 @@ def function(self, E):
if np.any(bifs):
cts[bifs] = splev(
E[bifs],
(self.__knots, self.fine_structure_coeff.value + (0,) * 4, 3))
(self.__knots, self.fine_structure_coeff.value + (0,) * 4, 3),
)
# The cross-section is set to 0 in the fine structure region
itab = (E < Emax) & (E >= ifsx2)
else:
Expand Down Expand Up @@ -530,6 +536,8 @@ def get_fine_structure_as_signal1D(self):

def as_dictionary(self, fullcopy=True):
dic = super().as_dictionary(fullcopy=fullcopy)
dic["fine_structure_components"] = [t.name for t in self.fine_structure_components]
dic["fine_structure_components"] = [
t.name for t in self.fine_structure_components
]
dic["_whitelist"]["fine_structure_components"] = ""
return dic
Loading
Loading