Skip to content

Commit

Permalink
Replace deprecated libraries
Browse files Browse the repository at this point in the history
  • Loading branch information
rayosborn committed Aug 9, 2024
1 parent e5fef6a commit 87440e5
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 31 deletions.
4 changes: 1 addition & 3 deletions src/nexpy/gui/datadialogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
import numbers
import os
import shutil
from importlib.resources import files as package_files
from operator import attrgetter
from pathlib import Path

import matplotlib as mpl
import numpy as np
import pkg_resources
from matplotlib.legend import Legend
from matplotlib.rcsetup import validate_aspect, validate_float
from nexusformat.nexus import (NeXusError, NXattr, NXdata, NXentry, NXfield,
Expand Down Expand Up @@ -1875,9 +1875,7 @@ def accept(self):
output[output == str(np.nan)] = ''
np.savetxt(fname, output, header=header, delimiter=self.delimiter,
comments='', fmt='%s')

logging.info(f"Data saved as '{fname}'")
super().accept()


class LockDialog(NXDialog):
Expand Down
31 changes: 16 additions & 15 deletions src/nexpy/gui/plotview.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.colors import LogNorm, Normalize, SymLogNorm
from matplotlib.figure import Figure
from matplotlib.image import imread
from matplotlib.lines import Line2D
from matplotlib.ticker import AutoLocator, LogLocator, ScalarFormatter
from packaging.version import parse as pv
from packaging.version import Version
from PIL import Image

from .pyqt import QtCore, QtGui, QtWidgets

Expand Down Expand Up @@ -67,8 +67,8 @@
ProjectionDialog, ScanDialog, StyleDialog)
from .utils import (boundaries, centers, divgray_map, find_nearest,
fix_projection, get_color, in_dark_mode, iterable,
keep_data, parula_map, report_error, report_exception,
resource_file, resource_icon, xtec_map)
keep_data, load_image, parula_map, report_error,
report_exception, resource_file, resource_icon, xtec_map)
from .widgets import (NXCheckBox, NXcircle, NXComboBox, NXDoubleSpinBox,
NXellipse, NXLabel, NXpolygon, NXPushButton, NXrectangle,
NXSlider, NXSpinBox)
Expand All @@ -86,7 +86,7 @@
'seismic', 'coolwarm', 'twilight', 'divgray', # diverging
'RdBu', 'RdYlBu', 'RdYlGn']

if pv(mpl.__version__) >= pv('3.5.0'):
if Version(mpl.__version__) >= Version('3.5.0'):
mpl.colormaps.register(parula_map())
mpl.colormaps.register(xtec_map())
mpl.colormaps.register(divgray_map())
Expand Down Expand Up @@ -125,8 +125,9 @@
'o': 'circle', 's': 'square', 'D': 'diamond', 'H': 'hexagon',
'v': 'triangle_down', '^': 'triangle_up', '<': 'triangle_left',
'>': 'triangle_right', 'None': 'None'}
logo = imread(resource_file('NeXpy.png'))[180:880, 50:1010]
warnings.filterwarnings("ignore", category=DeprecationWarning)
logo = load_image(resource_file('NeXpy.png'))[180:880, 50:1010]
logo["title"] = '"NeXpy"'
# warnings.filterwarnings("ignore", category=DeprecationWarning)


def new_figure_manager(label=None, *args, **kwargs):
Expand Down Expand Up @@ -606,7 +607,7 @@ def deactivate(self):

def display_logo(self):
"""Display the NeXpy logo in the plotting pane."""
self.plot(NXdata(logo, title='NeXpy'), image=True)
self.plot(logo, image=True)
self.ax.xaxis.set_visible(False)
self.ax.yaxis.set_visible(False)
self.ax.title.set_visible(False)
Expand Down Expand Up @@ -1087,7 +1088,7 @@ def plot_image(self, over=False, **opts):
else:
opts['interpolation'] = self.interpolation

if pv(mpl.__version__) >= pv('3.5.0'):
if Version(mpl.__version__) >= Version('3.5.0'):
cm = copy.copy(mpl.colormaps[self.cmap])
else:
cm = copy.copy(get_cmap(self.cmap))
Expand Down Expand Up @@ -1222,7 +1223,7 @@ def set_data_limits(self):
self.vaxis.lo = 0.5
else:
self.vaxis.lo = -0.5
if pv(mpl.__version__) >= pv('3.5.0'):
if Version(mpl.__version__) >= Version('3.5.0'):
nc = len(mpl.colormaps[self.cmap].colors)
else:
nc = len(get_cmap(self.cmap).colors)
Expand Down Expand Up @@ -1365,15 +1366,15 @@ def replot_axes(self, draw=True):

def update_colorbar(self):
if self.colorbar:
if pv(mpl.__version__) >= pv('3.1.0'):
if Version(mpl.__version__) >= Version('3.1.0'):
self.colorbar.update_normal(self.image)
else:
self.colorbar.set_norm(self.norm)
self.colorbar.update_bruteforce(self.image)
if self.vtab.qualitative:
vmin, vmax = [int(i+0.5) for i in self.image.get_clim()]
self.colorbar.set_ticks(range(vmin, vmax))
if pv(mpl.__version__) >= pv('3.5.0'):
if Version(mpl.__version__) >= Version('3.5.0'):
if self.cmap == 'xtec':
vmin, vmax = (0.5, self.vaxis.max_data+0.5)
else:
Expand Down Expand Up @@ -1515,7 +1516,7 @@ def symlog(self, linthresh=None, linscale=None, vmax=None):
self.vaxis.max = self.vaxis.hi = vmax
self.colorbar.locator = AutoLocator()
self.colorbar.formatter = ScalarFormatter()
if pv(mpl.__version__) >= pv('3.1.0'):
if Version(mpl.__version__) >= Version('3.1.0'):
self.image.set_norm(SymLogNorm(linthresh, linscale=linscale,
vmin=-vmax, vmax=vmax))
else:
Expand Down Expand Up @@ -3477,7 +3478,7 @@ def cmap(self, cmap):
if cmap is None:
cmap = self._cached_cmap
try:
if pv(mpl.__version__) >= pv('3.5.0'):
if Version(mpl.__version__) >= Version('3.5.0'):
cm = copy.copy(mpl.colormaps[cmap])
else:
cm = copy.copy(get_cmap(cmap))
Expand Down Expand Up @@ -3901,7 +3902,7 @@ def __init__(self, canvas, parent=None, coordinates=True):

NavigationToolbar2.__init__(self, canvas)
if in_dark_mode() and (
pv(QtCore.__version__) <= pv('5.15')):
Version(QtCore.__version__) <= Version('5.15')):
self.setStyleSheet('color: black')
self.plotview = canvas.parent()
self.zoom()
Expand Down
27 changes: 14 additions & 13 deletions src/nexpy/gui/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from matplotlib import rcParams
from matplotlib.colors import colorConverter, hex2color, rgb2hex
from packaging.version import Version
from PIL import Image

from .pyqt import QtCore, QtGui, QtWidgets

Expand All @@ -42,8 +43,8 @@
fabio = None

from nexusformat.nexus import (NeXusError, NXcollection, NXdata, NXfield,
NXLock, NXLockException, NXnote,
nxgetconfig, nxload, nxsetconfig)
NXLock, NXLockException, NXnote, nxgetconfig,
nxload, nxsetconfig)

ansi_re = re.compile(r'\x1b' + r'\[([\dA-Fa-f;]*?)m')

Expand Down Expand Up @@ -131,8 +132,9 @@ def run_pythonw(script_path):
return
import platform
import warnings
from distutils.version import StrictVersion
if (StrictVersion(platform.release()) > StrictVersion('19.0.0') and

from packaging.version import Version
if (Version(platform.release()) > Version('19.0.0') and
'CONDA_PREFIX' in os.environ):
pythonw_path = Path(sys.exec_prefix).joinpath('bin', 'pythonw')
if pythonw_path.exists():
Expand Down Expand Up @@ -589,10 +591,9 @@ def cmyk_to_rgb(c, m, y, k):


def load_image(filename):
if os.path.splitext(filename.lower())[1] in ['.png', '.jpg', '.jpeg',
'.gif']:
from matplotlib.image import imread
im = imread(filename)
if Path(filename).suffix.lower() in ['.png', '.jpg', '.jpeg', '.gif']:
with Image.open(filename) as PIL_image:
im = np.array(PIL_image)
z = NXfield(im, name='z')
y = NXfield(range(z.shape[0]), name='y')
x = NXfield(range(z.shape[1]), name='x')
Expand Down Expand Up @@ -623,14 +624,14 @@ def load_image(filename):
for k, v in im.header.items():
if v or v == 0:
header[k] = v
data.header = header
data["header"] = header
if im.getclassname() == 'CbfImage':
note = NXnote(type='text/plain', file_name=filename)
note.data = im.header.pop('_array_data.header_contents', '')
note.description = im.header.pop(
note["data"] = im.header.pop('_array_data.header_contents', '')
note["description"] = im.header.pop(
'_array_data.header_convention', '')
data.CBF_header = note
data.title = filename
data["CBF_header"] = note
data["title"] = filename
return data


Expand Down

0 comments on commit 87440e5

Please sign in to comment.