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

config_checker update and linting for C408,C419,C405, C409, E721,F401,E722 #560

Open
wants to merge 47 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
53e8796
initial bare exception fix
alex-rakowski Nov 9, 2023
fbbc232
correcting multiple exception handling
alex-rakowski Nov 9, 2023
2212461
Changing to Exception if unsure
alex-rakowski Nov 10, 2023
51f078f
changing to assertion error
alex-rakowski Nov 10, 2023
db59746
removing TODO message
alex-rakowski Nov 10, 2023
be609b3
Changing to a Exception
alex-rakowski Nov 10, 2023
08957ff
changing from ValueError to Exception
alex-rakowski Nov 10, 2023
e6b6ade
black
alex-rakowski Nov 10, 2023
857715a
ruff C408
alex-rakowski Nov 10, 2023
7892191
ruff --select C419
alex-rakowski Nov 10, 2023
4288ca2
C409 C405
alex-rakowski Nov 10, 2023
1a00dd1
trailing commas
alex-rakowski Nov 10, 2023
dfa7546
black
alex-rakowski Nov 10, 2023
79b2559
E721
alex-rakowski Nov 10, 2023
0b20634
F401 - unused imports
alex-rakowski Nov 10, 2023
d3ccf03
black
alex-rakowski Nov 10, 2023
9022bee
more E721
alex-rakowski Nov 10, 2023
83a727a
Merge branch 'bare_exceptions' into unnecessary-collection-calls
alex-rakowski Nov 10, 2023
15f387f
Merge pull request #16 from alex-rakowski/unnecessary-collection-calls
alex-rakowski Nov 10, 2023
dd1a74b
removing old comment
alex-rakowski Nov 10, 2023
9657c42
adding KeyError
alex-rakowski Nov 10, 2023
dbfa1b2
adding KeyError to correct place ...
alex-rakowski Nov 10, 2023
6b5dfec
adding hdf5plugin back in
alex-rakowski Nov 10, 2023
89ad26a
Changing to Exception to catch more errors
alex-rakowski Nov 10, 2023
ed34a99
changning cupy GPU count method
alex-rakowski Nov 10, 2023
5275729
black
alex-rakowski Nov 10, 2023
96c96ae
using importlib to populate requirements
alex-rakowski Nov 13, 2023
f304a52
Merge branch 'dev' into bare_exceptions
alex-rakowski Nov 13, 2023
03e9e61
changing find_spec to try except
alex-rakowski Nov 14, 2023
436d1e4
adding suspected KeyError to TODO
alex-rakowski Nov 14, 2023
5f5d895
F811, F523/F524, F841, F741 - Corrections
alex-rakowski Nov 16, 2023
98c21d2
updating to autoscrape optional depends
alex-rakowski Nov 17, 2023
0f9b096
fixing typo in docstring
alex-rakowski Nov 17, 2023
dc9c632
removing unused vars
alex-rakowski Nov 17, 2023
4936f9e
Merge branch 'dev' of github.com:py4dstem/py4DSTEM into crystal-forma…
alex-rakowski Nov 17, 2023
03986fa
adding generic version extra tests
alex-rakowski Nov 17, 2023
8e4f7c9
removing TODO
alex-rakowski Nov 17, 2023
0a77665
ModuleNotFoundErrors
alex-rakowski Nov 17, 2023
92c6942
removing TODOS
alex-rakowski Nov 17, 2023
c280c8e
changing logic for print(Running Extra Checks run)
alex-rakowski Nov 17, 2023
f1a9b3a
cleaning up old commented out code
alex-rakowski Nov 17, 2023
ffa70f9
remove unused imports
alex-rakowski Nov 17, 2023
0b10f48
fixing import test
alex-rakowski Nov 18, 2023
83453df
Merge remote-tracking branch 'upstream/dev' into bare_exceptions
sezelt Mar 8, 2024
19914f6
missing import
sezelt Mar 8, 2024
9397208
other missing import
sezelt Mar 8, 2024
9201154
Merge branch 'crystal-format-fixes' into bare_exceptions
sezelt Mar 8, 2024
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
2 changes: 1 addition & 1 deletion py4DSTEM/braggvectors/braggvectors.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Defines the BraggVectors class

from py4DSTEM.data import Data
from emdfile import Custom, PointListArray, PointList, Metadata
from emdfile import Custom, PointListArray, Metadata
from py4DSTEM.braggvectors.braggvector_methods import BraggVectorMethods
from os.path import basename
import numpy as np
Expand Down
2 changes: 1 addition & 1 deletion py4DSTEM/braggvectors/diskdetection.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def find_Bragg_disks(
mode = "dp"
elif data.ndim == 3:
mode = "dp_stack"
except:
except Exception:
er = f"entry {data} for `data` could not be parsed"
raise Exception(er)

Expand Down
42 changes: 24 additions & 18 deletions py4DSTEM/braggvectors/diskdetection_aiml.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,13 @@
"""

import os
import glob
import json
import shutil
import numpy as np

from scipy.ndimage import gaussian_filter
from time import time
from numbers import Number

from emdfile import tqdmnd, PointList, PointListArray
from emdfile import tqdmnd
from py4DSTEM.braggvectors.braggvectors import BraggVectors
from py4DSTEM.data import QPoints
from py4DSTEM.process.utils import get_maxima_2D
Expand Down Expand Up @@ -103,12 +100,12 @@ def find_Bragg_disks_aiml_single_DP(
"""
try:
import crystal4D
except:
except ModuleNotFoundError:
raise ImportError("Import Error: Please install crystal4D before proceeding")
try:
import tensorflow as tf
except:
raise ImportError(
except ModuleNotFoundError:
raise ModuleNotFoundError(
"Please install tensorflow before proceeding - please check "
+ "https://www.tensorflow.org/install"
+ "for more information"
Expand Down Expand Up @@ -256,7 +253,7 @@ def find_Bragg_disks_aiml_selected(

try:
import crystal4D
except:
except ModuleNotFoundError:
raise ImportError("Import Error: Please install crystal4D before proceeding")
alex-rakowski marked this conversation as resolved.
Show resolved Hide resolved

assert len(Rx) == len(Ry)
Expand Down Expand Up @@ -433,7 +430,7 @@ def find_Bragg_disks_aiml_serial(

try:
import crystal4D
except:
except ModuleNotFoundError:
alex-rakowski marked this conversation as resolved.
Show resolved Hide resolved
raise ImportError("Import Error: Please install crystal4D before proceeding")

# Make the peaks PointListArray
Expand Down Expand Up @@ -559,7 +556,7 @@ def find_Bragg_disks_aiml(
model_path=None,
distributed=None,
CUDA=True,
**kwargs
**kwargs,
):
"""
Finds the Bragg disks in all diffraction patterns of datacube by AI/ML method. This method
Expand Down Expand Up @@ -643,8 +640,8 @@ def find_Bragg_disks_aiml(
"""
try:
import crystal4D
except:
raise ImportError("Please install crystal4D before proceeding")
except ModuleNotFoundError:
raise ImportError("Import Error: Please install crystal4D before proceeding")
alex-rakowski marked this conversation as resolved.
Show resolved Hide resolved

def _parse_distributed(distributed):
import os
Expand Down Expand Up @@ -840,7 +837,8 @@ def _integrate_disks(DP, maxima_x, maxima_y, maxima_int, int_window_radius=1):
disks.append(np.average(disk))
try:
disks = disks / max(disks)
except:
# TODO work out what exception would go here
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd guess this is a ZeroDivisionError, but I didn't want to guess I can remove the TODO if prefered.

except Exception:
pass
return (maxima_x, maxima_y, disks)

Expand Down Expand Up @@ -878,8 +876,8 @@ def _get_latest_model(model_path=None):

try:
import tensorflow as tf
except:
raise ImportError(
except ModuleNotFoundError:
raise ModuleNotFoundError(
"Please install tensorflow before proceeding - please check "
+ "https://www.tensorflow.org/install"
+ "for more information"
Expand All @@ -891,8 +889,12 @@ def _get_latest_model(model_path=None):
if model_path is None:
try:
os.mkdir("./tmp")
except:
except FileExistsError:
pass
except Exception as e:
# TODO work out if I want to pass or raise
alex-rakowski marked this conversation as resolved.
Show resolved Hide resolved
pass
# raise e
# download the json file with the meta data
download_file_from_google_drive("FCU-Net", "./tmp/model_metadata.json")
with open("./tmp/model_metadata.json") as f:
Expand All @@ -905,7 +907,10 @@ def _get_latest_model(model_path=None):
with open("./tmp/model_metadata_old.json") as f_old:
metaold = json.load(f_old)
file_id_old = metaold["file_id"]
except:
# TODO Double check this is correct Error
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO

except FileNotFoundError:
file_id_old = file_id
except Exception:
alex-rakowski marked this conversation as resolved.
Show resolved Hide resolved
file_id_old = file_id

if os.path.exists(file_path) and file_id == file_id_old:
Expand All @@ -921,7 +926,8 @@ def _get_latest_model(model_path=None):
download_file_from_google_drive(file_id, filename)
try:
shutil.unpack_archive(filename, "./tmp", format="zip")
except:
# TODO Work work what specific exception
alex-rakowski marked this conversation as resolved.
Show resolved Hide resolved
except Exception:
pass
model_path = file_path
os.rename("./tmp/model_metadata.json", "./tmp/model_metadata_old.json")
Expand Down
15 changes: 8 additions & 7 deletions py4DSTEM/braggvectors/diskdetection_aiml_cuda.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@

from emdfile import tqdmnd
from py4DSTEM.braggvectors.braggvectors import BraggVectors
from emdfile import PointList, PointListArray
from py4DSTEM.data import QPoints
from emdfile import PointList
from py4DSTEM.braggvectors.kernels import kernels
from py4DSTEM.braggvectors.diskdetection_aiml import _get_latest_model

Expand All @@ -22,8 +21,8 @@

try:
import tensorflow as tf
except:
raise ImportError(
except ModuleNotFoundError:
raise ModuleNotFoundError(
"Please install tensorflow before proceeding - please check "
+ "https://www.tensorflow.org/install"
+ "for more information"
Expand Down Expand Up @@ -265,7 +264,7 @@ def _find_Bragg_disks_aiml_single_DP_CUDA(
blocks=None,
threads=None,
model_path=None,
**kwargs
**kwargs,
):
"""
Finds the Bragg disks in single DP by AI/ML method. This method utilizes FCU-Net
Expand Down Expand Up @@ -637,7 +636,8 @@ def upsampled_correlation_cp(imageCorr, upsampleFactor, xyShift):
)
dx = (icc[2, 1] - icc[0, 1]) / (4 * icc[1, 1] - 2 * icc[2, 1] - 2 * icc[0, 1])
dy = (icc[1, 2] - icc[1, 0]) / (4 * icc[1, 1] - 2 * icc[1, 2] - 2 * icc[1, 0])
except:
# TODO I think this is just the IndexError
except Exception:
dx, dy = (
0,
0,
Expand Down Expand Up @@ -733,6 +733,7 @@ def _integrate_disks_cp(DP, maxima_x, maxima_y, maxima_int, int_window_radius=1)
disks.append(np.average(disk))
try:
disks = disks / max(disks)
except:
# TODO work out what exception to use, ZeroDivisionError
except Exception:
pass
return (maxima_x, maxima_y, disks)
3 changes: 2 additions & 1 deletion py4DSTEM/braggvectors/diskdetection_cuda.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,8 @@ def upsampled_correlation(imageCorr, upsampleFactor, xyShift):
dy = (icc[1, 2] - icc[1, 0]) / (
4 * icc[1, 1] - 2 * icc[1, 2] - 2 * icc[1, 0]
)
except:
# TODO Work out what exception to use IndexError
except Exception:
dx, dy = (
0,
0,
Expand Down
14 changes: 3 additions & 11 deletions py4DSTEM/braggvectors/diskdetection_parallel_new.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
import numpy as np
import matplotlib.pyplot as plt
import h5py
import time
import dill

import dask
import dask.array as da
import dask.config
from dask import delayed
from dask.distributed import Client, LocalCluster
from dask.diagnostics import ProgressBar

# import dask.bag as db

# import distributed
from distributed.protocol.serialize import register_serialization_family
import distributed

import py4DSTEM
from emdfile import PointListArray, PointList
from emdfile import PointListArray
from py4DSTEM.braggvectors.diskdetection import _find_Bragg_disks_single_DP_FK


Expand Down Expand Up @@ -100,7 +92,7 @@ def beta_parallel_disk_detection(
close_dask_client=False,
return_dask_client=True,
*args,
**kwargs
**kwargs,
):
"""
This is not fully validated currently so may not work, please report bugs on the py4DSTEM github page.
Expand Down Expand Up @@ -225,7 +217,7 @@ def beta_parallel_disk_detection(
probe_kernel_FT=dask_probe_delayed[0, 0],
# probe_kernel_FT=delayed_probe_kernel_FT,
*args,
**kwargs
**kwargs,
) # passing through args from earlier or should I use
# corrPower=corrPower,
# sigma=sigma_gaussianFilter,
Expand Down
4 changes: 2 additions & 2 deletions py4DSTEM/braggvectors/threshold.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def threshold_Braggpeaks(
pattern
"""
assert all(
[item in pointlistarray.dtype.fields for item in ["qx", "qy", "intensity"]]
item in pointlistarray.dtype.fields for item in ["qx", "qy", "intensity"]
), "pointlistarray must include the coordinates 'qx', 'qy', and 'intensity'."
for Rx, Ry in tqdmnd(
pointlistarray.shape[0],
Expand Down Expand Up @@ -113,7 +113,7 @@ def universal_threshold(
assert isinstance(pointlistarray, PointListArray)
assert metric in ("maximum", "average", "median", "manual")
assert all(
[item in pointlistarray.dtype.fields for item in ["qx", "qy", "intensity"]]
item in pointlistarray.dtype.fields for item in ["qx", "qy", "intensity"]
), "pointlistarray must include the coordinates 'qx', 'qy', and 'intensity'."
_pointlistarray = pointlistarray.copy()
if name is None:
Expand Down
12 changes: 5 additions & 7 deletions py4DSTEM/data/calibration.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
# Defines the Calibration class, which stores calibration metadata

import numpy as np
from numbers import Number
from typing import Optional
from warnings import warn

from emdfile import Metadata, Root
from py4DSTEM.data.propagating_calibration import call_calibrate
Expand Down Expand Up @@ -505,7 +503,7 @@ def get_origin(self, rx=None, ry=None):
qx0 = self._get_value("qx0", rx, ry)
qy0 = self._get_value("qy0", rx, ry)
ans = (qx0, qy0)
if any([x is None for x in ans]):
if any(x is None for x in ans):
ans = None
return ans

Expand All @@ -518,7 +516,7 @@ def get_origin_shift(self, rx=None, ry=None):
qx0 = self._get_value("qx0_shift", rx, ry)
qy0 = self._get_value("qy0_shift", rx, ry)
ans = (qx0, qy0)
if any([x is None for x in ans]):
if any(x is None for x in ans):
ans = None
return ans

Expand All @@ -540,7 +538,7 @@ def get_origin_meas(self, rx=None, ry=None):
qx0 = self._get_value("qx0_meas", rx, ry)
qy0 = self._get_value("qy0_meas", rx, ry)
ans = (qx0, qy0)
if any([x is None for x in ans]):
if any(x is None for x in ans):
ans = None
return ans

Expand Down Expand Up @@ -615,7 +613,7 @@ def get_ellipse(self, rx=None, ry=None):
b = self.get_b(rx, ry)
theta = self.get_theta(rx, ry)
ans = (a, b, theta)
if any([x is None for x in ans]):
if any(x is None for x in ans):
ans = None
return ans

Expand Down Expand Up @@ -778,7 +776,7 @@ def get_probe_param(self):
qx0 = self._get_value("qx0")
qy0 = self._get_value("qy0")
ans = (probe_semiangle, qx0, qy0)
if any([x is None for x in ans]):
if any(x is None for x in ans):
ans = None
return ans

Expand Down
4 changes: 2 additions & 2 deletions py4DSTEM/datacube/datacube.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
)
from typing import Optional, Union

from emdfile import Array, Metadata, Node, Root, tqdmnd
from emdfile import Array, Metadata, Node, tqdmnd
from py4DSTEM.data import Data, Calibration
from py4DSTEM.datacube.virtualimage import DataCubeVirtualImager
from py4DSTEM.datacube.virtualdiffraction import DataCubeVirtualDiffraction
Expand Down Expand Up @@ -653,7 +653,7 @@ def get_probe_size(
"dp_mean" in self.treekeys
), "calculate .get_dp_mean() or pass a `dp` arg"
DP = self.tree("dp_mean").data
elif type(dp) == str:
elif isinstance(dp, str):
assert dp in self.treekeys, f"mode {dp} not found in the tree"
DP = self.tree(dp)
elif type(dp) == np.ndarray:
Expand Down
2 changes: 1 addition & 1 deletion py4DSTEM/datacube/virtualimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ def position_detector(
try:
image = self.tree(k)
break
except:
except AssertionError:
pass
if image is None:
image = self[0, 0]
Expand Down
3 changes: 2 additions & 1 deletion py4DSTEM/io/filereaders/read_K2.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ def __init__(
# this may be wrong for binned data... in which case the reader doesn't work anyway!
Q_Nx = gtg.allTags[".SI Image Tags.Acquisition.Parameters.Detector.height"]
Q_Ny = gtg.allTags[".SI Image Tags.Acquisition.Parameters.Detector.width"]
except:
# TODO check this is the correct error type
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can remove as Exception will handle what we want, but I think it would be better to add the expected exception/s in the future, but I'm not familiar enough to check/test

except (ValueError, KeyError):
print("Warning: diffraction pattern shape not detected!")
print("Assuming 1920x1792 as the diffraction pattern size!")
Q_Nx = 1792
Expand Down
2 changes: 1 addition & 1 deletion py4DSTEM/io/filereaders/read_arina.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import h5py
import hdf5plugin
alex-rakowski marked this conversation as resolved.
Show resolved Hide resolved
import hdf5plugin # noqa: F401
import numpy as np
from py4DSTEM.datacube import DataCube
from py4DSTEM.preprocess.utils import bin2D
Expand Down
1 change: 0 additions & 1 deletion py4DSTEM/io/filereaders/read_dm.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Reads a digital micrograph 4D-STEM dataset

import numpy as np
from pathlib import Path
from ncempy.io import dm
from emdfile import tqdmnd, Array

Expand Down
2 changes: 1 addition & 1 deletion py4DSTEM/io/filereaders/read_mib.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def load_mib(
reshape=True,
flip=True,
scan=(256, 256),
**kwargs
**kwargs,
):
"""
Read a MIB file and return as py4DSTEM DataCube.
Expand Down
Loading