Skip to content

Commit

Permalink
replacing pkg_resources with importlib
Browse files Browse the repository at this point in the history
  • Loading branch information
FrederikLizakJohansen committed Aug 27, 2024
1 parent 3ea4796 commit d5308ce
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 42 deletions.
61 changes: 30 additions & 31 deletions debyecalculator/debye_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import hashlib
import time
import yaml
import pkg_resources
import importlib.resources
import warnings
from glob import glob
from datetime import datetime, timezone
Expand Down Expand Up @@ -174,8 +174,7 @@ def __init__(
self.q = torch.arange(self.qmin, self.qmax, self.qstep).unsqueeze(-1).to(device=self.device)
self.r = torch.arange(self.rmin, self.rmax, self.rstep).unsqueeze(-1).to(device=self.device)

# Load form factor coefficients
with open(pkg_resources.resource_filename(__name__, 'utility/elements_info_neutrons.yaml'), 'r') as yaml_file:
with importlib.resources.open_text('debyecalculator.utility', 'elements_info.yaml') as yaml_file:
self.FORM_FACTOR_COEF = yaml.safe_load(yaml_file)

# Form factor coefficients
Expand Down Expand Up @@ -1145,9 +1144,9 @@ def interact(
radiation_type = self.radiation_type
profile = False

with open(pkg_resources.resource_filename(__name__, 'display_assets/choose_hardware.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'choose_hardware.png') as f:
choose_hardware_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/batch_size.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'batch_size.png') as f:
batch_size_img = f.read()

""" Utility widgets """
Expand Down Expand Up @@ -1175,7 +1174,7 @@ def update_example_files(change):
file_list = '<strong>Uploaded Files:</strong><br>'

# CIF Example
with open(pkg_resources.resource_filename(__name__, '../data/AntiFluorite_Co2O.cif'), 'rb') as f:
with importlib.resources.open_binary('data', 'AntiFluorite_Co2O.cif') as f:
example_dict = {}
example_dict['content'] = f.read()
example_dict['name'] = 'AntiFluorite_Co2O.cif'
Expand All @@ -1186,7 +1185,7 @@ def update_example_files(change):
create_file_widgets(example_dict, file_widgets)

# XYZ Example
with open(pkg_resources.resource_filename(__name__, '../data/AntiFluorite_Co2O_r10.xyz'), 'rb') as f:
with importlib.resources.open_binary('data', 'AntiFluorite_Co2O_r10.xyz') as f:
example_dict = {}
example_dict['content'] = f.read()
example_dict['name'] = 'AntiFluorite_Co2O_r10.xyz'
Expand Down Expand Up @@ -1249,31 +1248,31 @@ def update_example_files(change):
""" Scattering Options Tab """

# Load display_assets
with open(pkg_resources.resource_filename(__name__, 'display_assets/qslider.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'qslider.png') as f:
qslider_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/rslider.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'rslider.png') as f:
rslider_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/qdamp.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'qdamp.png') as f:
qdamp_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/global_biso.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'global_biso.png') as f:
global_biso_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/a.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'a.png') as f:
a_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/a_inv.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'a_inv.png') as f:
a_inv_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/a_sq.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'a_sq.png') as f:
a_sq_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/qstep.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'qstep.png') as f:
qstep_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/rstep.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'rstep.png') as f:
rstep_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/rthres.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'rthres.png') as f:
rthres_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/radiation_type.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'radiation_type.png') as f:
radiation_type_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/scattering_parameters.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'scattering_parameters.png') as f:
scattering_parameters_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/presets.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'presets.png') as f:
presets_img = f.read()

# Radiation
Expand Down Expand Up @@ -1465,19 +1464,19 @@ def update_example_files(change):
""" Plotting Options """

# Load display display_assets
with open(pkg_resources.resource_filename(__name__, 'display_assets/iq_scaling.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'qstep.png') as f:
iq_scaling_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/show_hide.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'show_hide.png') as f:
show_hide_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/max_norm.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'max_norm.png') as f:
max_norm_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/iq.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'iq.png') as f:
iq_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/sq.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'sq.png') as f:
sq_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/fq.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'fq.png') as f:
fq_img = f.read()
with open(pkg_resources.resource_filename(__name__, 'display_assets/gr.png'), 'rb') as f:
with importlib.resources.open_binary('debyecalculator.display_assets', 'gr.png') as f:
gr_img = f.read()

# Y-axis I(Q) scale button
Expand Down Expand Up @@ -1783,7 +1782,7 @@ def update_figure(debye_outputs, _unity_sq=True):
xseries.append(do[1]) # q
iq_ = do[2] if not normalize_iq.value else do[2]/max(do[2])
yseries.append(iq_) # iq
xlabels.append('$Q$ [$\AA^{-1}$]')
xlabels.append('$Q$ [$Å^{-1}$]')
ylabels.append('$I(Q)$' + normalize_iq_text)
if scale_type_button.value == 'logarithmic':
scales.append('log')
Expand All @@ -1796,7 +1795,7 @@ def update_figure(debye_outputs, _unity_sq=True):
xseries.append(do[1]) # q
sq_ = do[3] if not normalize_sq.value else do[3]/max(do[3])
yseries.append(sq_) # sq
xlabels.append('$Q$ [$\AA^{-1}$]')
xlabels.append('$Q$ [$Å^{-1}$]')
ylabels.append('$S(Q)$' + normalize_sq_text)
scales.append('linear')
titles.append('Structure Function, S(Q)')
Expand All @@ -1805,7 +1804,7 @@ def update_figure(debye_outputs, _unity_sq=True):
xseries.append(do[1]) # q
fq_ = do[4] if not normalize_fq.value else do[4]/max(do[4])
yseries.append(fq_) # fq
xlabels.append('$Q$ [$\AA^{-1}$]')
xlabels.append('$Q$ [$Å^{-1}$]')
ylabels.append('$F(Q)$'+ normalize_fq_text)
scales.append('linear')
titles.append('Reduced Structure Function, F(Q)')
Expand All @@ -1814,7 +1813,7 @@ def update_figure(debye_outputs, _unity_sq=True):
xseries.append(do[0]) # r
gr_ = do[5] if not normalize_gr.value else do[5]/max(do[5])
yseries.append(gr_) # gr
xlabels.append('$r$ [$\AA$]')
xlabels.append('$r$ [$Å$]')
ylabels.append('$G(r)$' + normalize_gr_text)
scales.append('linear')
titles.append('Reduced Pair Distribution Function, G(r)')
Expand Down
4 changes: 2 additions & 2 deletions debyecalculator/test_debye_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
from debyecalculator.utility.generate import generate_nanoparticles
import numpy as np
from ase.io import read
import pkg_resources
import importlib.resources
import yaml
import math

# Elements to atomic numbers map
with open(pkg_resources.resource_filename(__name__, 'utility/elements_info_xrays.yaml'), 'r') as yaml_file:
with importlib.resources.open_text('debyecalculator.utility', 'elements_info.yaml') as yaml_file:
element_info = yaml.safe_load(yaml_file)
element_to_atomic_number = {}
for i, (key, value) in enumerate(element_info.items()):
Expand Down
32 changes: 23 additions & 9 deletions debyecalculator/utility/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from typing import Union, List
from collections import namedtuple
import yaml
import pkg_resources
import importlib.resources
import warnings
from tqdm.auto import tqdm

Expand Down Expand Up @@ -149,11 +149,15 @@ def generate_nanoparticles(
device = device

# Fetch atomic numbers and radii
with open(pkg_resources.resource_filename(__name__, 'elements_info_xrays.yaml'), 'r') as yaml_file:
with importlib.resources.open_text('debyecalculator.utility', 'elements_info.yaml') as yaml_file:
elements_info = yaml.safe_load(yaml_file)

# Fix radii type
if isinstance(radii, list):
if isinstance(radii, np.ndarray):
radii = [float(r) for r in radii]
elif torch.is_tensor(radii):
radii = [float(r) for r in radii]
elif isinstance(radii, list):
radii = [float(r) for r in radii]
elif isinstance(radii, float):
radii = [radii]
Expand Down Expand Up @@ -388,6 +392,7 @@ def generate_core_shell_models_fixed_size(
core_shell_ratios=[0.3, 0.5, 0.7],
radius=10.0,
half_sphere=False,
crystalstructure = 'fcc',
):
"""
Generates a list of ASE core-shell models with a fixed particle size and varying core-shell ratios.
Expand All @@ -400,13 +405,14 @@ def generate_core_shell_models_fixed_size(
- core_shell_ratios (list of float): A list of core-to-particle radius ratios to generate.
- radius (float): The fixed maximum radius of the particle.
- half_sphere (bool): Whether to return half of the particle sphere.
- crystalstructure (str): Must be one of sc, fcc, bcc, tetragonal, bct, hcp, rhombohedral, orthorhombic, mcl, diamond, zincblend, rocksalt, cesiumchloride, fluorite or wurtzite.
Returns:
- models (list of ASE Atoms objects): A list of core-shell particles with varying core-shell ratios.
"""

# Create a bulk cubic crystal of the core element
structure = bulk(core_element, 'fcc', a=lattice_constant, cubic=True).repeat(size)
structure = bulk(core_element, crystalstructure, a=lattice_constant, cubic=True).repeat(size)
center_of_geometry = structure.get_positions().mean(axis=0)
structure.translate(-center_of_geometry)

Expand Down Expand Up @@ -451,6 +457,7 @@ def generate_core_shell_models(
shell_thicknesses=[1.0, 2.0, 3.0],
radius=10.0,
half_sphere=False,
crystalstructure='fcc',
):
"""
Generates a list of ASE core-shell models with varying shell thicknesses.
Expand All @@ -464,13 +471,14 @@ def generate_core_shell_models(
- shell_thicknesses (list of float): A list of shell thicknesses to generate.
- radius (float): The maximum radius of the particle.
- half_sphere (bool): Whether to return half of the particle sphere.
- crystalstructure (str): Must be one of sc, fcc, bcc, tetragonal, bct, hcp, rhombohedral, orthorhombic, mcl, diamond, zincblend, rocksalt, cesiumchloride, fluorite or wurtzite.
Returns:
- models (list of ASE Atoms objects): A list of core-shell particles with varying shell thicknesses.
"""

# Create a bulk cubic crystal of the core element
structure = bulk(core_element, 'fcc', a=lattice_constant, cubic=True).repeat(size)
structure = bulk(core_element, crystalstructure, a=lattice_constant, cubic=True).repeat(size)
center_of_geometry = structure.get_positions().mean(axis=0)
structure.translate(-center_of_geometry)

Expand Down Expand Up @@ -511,6 +519,7 @@ def generate_substitutional_alloy_models(
substitution_ratios=[0.1, 0.2, 0.3],
radius=10.0,
half_sphere=False,
crystalstructure='fcc',
seed=None,
):
"""
Expand All @@ -525,14 +534,15 @@ def generate_substitutional_alloy_models(
- substitution_ratios (list of float): A list of substitution ratios to generate.
- radius (float): The fixed maximum radius of the particle.
- half_sphere (bool): Whether to return half of the particle sphere.
- crystalstructure (str): Must be one of sc, fcc, bcc, tetragonal, bct, hcp, rhombohedral, orthorhombic, mcl, diamond, zincblend, rocksalt, cesiumchloride, fluorite or wurtzite.
- seed (int, None): If not None, seed to be used to choose substituted atoms.
Returns:
- models (list of ASE Atoms objects): A list of spherical particles with varying substitution ratios.
"""

# Create a bulk cubic crystal of the base element
structure = bulk(base_element, 'fcc', a=lattice_constant, cubic=True).repeat(size)
structure = bulk(base_element, crystalstructure, a=lattice_constant, cubic=True).repeat(size)

# Center the structure
center_of_geometry = structure.get_positions().mean(axis=0)
Expand Down Expand Up @@ -579,7 +589,8 @@ def generate_periodic_plane_substitution(
size=(7, 7, 7),
radius=10.0,
plane_spacing=3,
plane_orientation='z'
plane_orientation='z',
crystalstructure='fcc',
):
"""
Generates a spherical particle with periodic planes of substituted atoms.
Expand All @@ -592,13 +603,14 @@ def generate_periodic_plane_substitution(
- radius (float): The fixed maximum radius of the particle.
- plane_spacing (int): The spacing between planes where substitution occurs.
- plane_orientation (str): The orientation of the planes ('x', 'y', or 'z').
- crystalstructure (str): Must be one of sc, fcc, bcc, tetragonal, bct, hcp, rhombohedral, orthorhombic, mcl, diamond, zincblend, rocksalt, cesiumchloride, fluorite or wurtzite.
Returns:
- particle (ASE Atoms object): The spherical particle with periodic planes of substituted atoms, cut in half for visualization.
"""

# Create a bulk cubic crystal of the base element
structure = bulk(base_element, 'fcc', a=lattice_constant, cubic=True).repeat(size)
structure = bulk(base_element, crystalstructure, a=lattice_constant, cubic=True).repeat(size)

# Center the structure
center_of_geometry = structure.get_positions().mean(axis=0)
Expand Down Expand Up @@ -626,6 +638,7 @@ def generate_spherical_particle(
lattice_constant=3.0,
size=(7, 7, 7),
radius=10.0,
crystalstructure='fcc',
):
"""
Generates a spherical particle with periodic planes of substituted atoms.
Expand All @@ -635,13 +648,14 @@ def generate_spherical_particle(
- lattice_constant (float): The lattice constant of the crystal in angstroms.
- size (tuple): The size of the unit cell replication in each direction.
- radius (float): The fixed maximum radius of the particle.
- crystalstructure (str): Must be one of sc, fcc, bcc, tetragonal, bct, hcp, rhombohedral, orthorhombic, mcl, diamond, zincblend, rocksalt, cesiumchloride, fluorite or wurtzite.
Returns:
- particle (ASE Atoms object): The spherical particle.
"""

# Create a bulk cubic crystal of the base element
structure = bulk(element, 'fcc', a=lattice_constant, cubic=True).repeat(size)
structure = bulk(element, crystalstructure, a=lattice_constant, cubic=True).repeat(size)

# Center the structure
center_of_geometry = structure.get_positions().mean(axis=0)
Expand Down

0 comments on commit d5308ce

Please sign in to comment.