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

Small coding style improvements #659

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
730b4a5
Port over correct changes from code-improvements
kevindlewis23 Jul 1, 2024
772aa37
pep8 fix
kevindlewis23 Jul 1, 2024
c1d1053
null to None fix
kevindlewis23 Jul 1, 2024
0500bd1
Revert "pep8 fix"
kevindlewis23 Jul 1, 2024
7914fd2
Revert "Revert "pep8 fix""
kevindlewis23 Jul 1, 2024
68aed16
Revert "null to None fix"
kevindlewis23 Jul 1, 2024
6ea44a4
Revert null change
kevindlewis23 Jul 1, 2024
c24fd9c
Replaced underscored names with just underscores
kevindlewis23 Jul 1, 2024
8e4b200
Get command change
kevindlewis23 Jul 1, 2024
0d1a11f
Fixes
kevindlewis23 Jul 1, 2024
30e9876
misorientation specify typing
kevindlewis23 Jul 1, 2024
3c783df
minor change
kevindlewis23 Jul 1, 2024
3f5388a
Marked unused parameters
kevindlewis23 Jul 1, 2024
c34df60
Port over correct changes from code-improvements
kevindlewis23 Jul 1, 2024
084a112
pep8 fix
kevindlewis23 Jul 1, 2024
1d0ba5b
null to None fix
kevindlewis23 Jul 1, 2024
47d02f4
Revert "pep8 fix"
kevindlewis23 Jul 1, 2024
2e3bf80
Revert "Revert "pep8 fix""
kevindlewis23 Jul 1, 2024
9232822
Revert "null to None fix"
kevindlewis23 Jul 1, 2024
f2b3640
Revert null change
kevindlewis23 Jul 1, 2024
dd2af53
Replaced underscored names with just underscores
kevindlewis23 Jul 1, 2024
120c62c
Get command change
kevindlewis23 Jul 1, 2024
807cb85
Fixes
kevindlewis23 Jul 1, 2024
c6ccb59
misorientation specify typing
kevindlewis23 Jul 1, 2024
2f06a24
minor change
kevindlewis23 Jul 1, 2024
49304b6
Marked unused parameters
kevindlewis23 Jul 1, 2024
a6378c4
Merge branch 'non-functional-style-changes' of https://github.com/Ver…
kevindlewis23 Jul 2, 2024
8f369e2
Undo accidental codecov changes
kevindlewis23 Jul 2, 2024
1e9764f
Remove unused fitting functions
kevindlewis23 Jul 2, 2024
1ce06a4
Merge branch 'master' of https://github.com/Verdant-Evolution/hexrd i…
kevindlewis23 Jul 2, 2024
4004d84
Merge branch 'master' of https://github.com/Verdant-Evolution/hexrd i…
kevindlewis23 Jul 2, 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
1 change: 0 additions & 1 deletion hexrd/cli/fit_grains.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,6 @@ def execute(args, parser):
gid_list = None
if args.grains is not None:
gid_list = [int(i) for i in args.grains.split(',')]
pass

fit_results = fit_grains(
cfg,
Expand Down
3 changes: 1 addition & 2 deletions hexrd/config/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
"sfacmin", "sfacmax", "pintmin", "pintmax"]
)


# Converting to none threw errors, maybe change later
class Null():
kevindlewis23 marked this conversation as resolved.
Show resolved Hide resolved
pass


null = Null()


Expand Down
5 changes: 1 addition & 4 deletions hexrd/convolution/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# Based on code from astropy
# Licensed under a 3-clause BSD style license
import ctypes
import numpy as np

class DiscretizationError(Exception):
"""
Expand All @@ -18,8 +16,7 @@ class KernelSizeError(Exception):
def has_even_axis(array):
if isinstance(array, (list, tuple)):
return not len(array) % 2
else:
return any(not axes_size % 2 for axes_size in array.shape)
return any(not axes_size % 2 for axes_size in array.shape)


def raise_even_kernel_exception():
Expand Down
4 changes: 1 addition & 3 deletions hexrd/distortion/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,10 @@ def __init__(cls, name, bases, attrs):

class Registry(object):
"""Registry for imageseries adapters"""
distortion_registry = dict()
distortion_registry = {}

@classmethod
def register(cls, acls):
"""Register adapter class"""
if acls.__name__ != 'DistortionBase':
cls.distortion_registry[acls.maptype] = acls

pass # end class
20 changes: 6 additions & 14 deletions hexrd/findorientations.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,6 @@ def generate_orientation_fibers(cfg, eta_ome):
del_ome = eta_ome.omegas[1] - eta_ome.omegas[0]
del_eta = eta_ome.etas[1] - eta_ome.etas[0]

params = dict(
bMat=bMat,
chi=chi,
csym=csym,
fiber_ndiv=fiber_ndiv)

# =========================================================================
# Labeling of spots from seed hkls
# =========================================================================
Expand All @@ -131,9 +125,12 @@ def generate_orientation_fibers(cfg, eta_ome):
ome_c = eta_ome.omeEdges[0] + (0.5 + coms[i][ispot][0])*del_ome
eta_c = eta_ome.etaEdges[0] + (0.5 + coms[i][ispot][1])*del_eta
input_p.append(np.hstack([this_hkl, this_tth, eta_c, ome_c]))
pass
pass
pass

params = dict(
ZackAttack614 marked this conversation as resolved.
Show resolved Hide resolved
bMat=bMat,
chi=chi,
csym=csym,
fiber_ndiv=fiber_ndiv)

# do the mapping
start = timeit.default_timer()
Expand Down Expand Up @@ -352,8 +349,6 @@ def quat_distance(x, y):
qbar[:, i] = rot.quatAverageCluster(
qfib_r[:, cl == i + 1], qsym
).flatten()
pass
pass

if algorithm in ('dbscan', 'ort-dbscan') and qbar.size/4 > 1:
logger.info("\tchecking for duplicate orientations...")
Expand All @@ -374,10 +369,7 @@ def quat_distance(x, y):
tmp[:, i] = rot.quatAverageCluster(
qbar[:, cl == i + 1].reshape(4, npts), qsym
).flatten()
pass
qbar = tmp
pass
pass

logger.info("clustering took %f seconds", timeit.default_timer() - start)
logger.info(
Expand Down
10 changes: 4 additions & 6 deletions hexrd/fitgrains.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def fit_grain_FF_reduced(grain_id):
num_refl_tot += len(valid_refl_ids)
num_refl_valid += sum(valid_refl_ids)

pass # now we have culled data
# now we have culled data

# CAVEAT: completeness from pullspots only; incl saturated and overlaps
# <JVB 2015-12-15>
Expand Down Expand Up @@ -220,8 +220,8 @@ def fit_grain_FF_reduced(grain_id):
plane_data.latVecOps['B'], plane_data.wavelength,
ome_period,
simOnly=False, return_value_flag=2)
pass # end conditional on fit
pass # end tolerance looping
# end conditional on fit
# end tolerance looping

if refit is not None:
# first get calculated x, y, ome from previous solution
Expand Down Expand Up @@ -279,7 +279,6 @@ def fit_grain_FF_reduced(grain_id):
]

num_refl_valid += sum(idx_new)
pass

# only execute fit if left with enough reflections
if num_refl_valid > 12:
Expand All @@ -297,8 +296,7 @@ def fit_grain_FF_reduced(grain_id):
plane_data.latVecOps['B'], plane_data.wavelength,
ome_period,
simOnly=False, return_value_flag=2)
pass
pass # close refit conditional
# close refit conditional
return grain_id, completeness, chisq, grain_params


Expand Down
6 changes: 1 addition & 5 deletions hexrd/fitting/calibration/laue.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,6 @@ def autopick_points(self, raw_img_dict, tth_tol=5., eta_tol=5.,
valid_hkls = hkls[gid][:, valid_refl]
valid_angs = angles[gid][valid_refl, :]
valid_energy = energy[gid][valid_refl]
# pass

# make patches
refl_patches = xrdutil.make_reflection_patches(
Expand Down Expand Up @@ -291,7 +290,6 @@ def autopick_points(self, raw_img_dict, tth_tol=5., eta_tol=5.,
#
else:
closest_peak_idx = 0
pass # end multipeak conditional
#
coms = coms[closest_peak_idx]
#
Expand Down Expand Up @@ -338,7 +336,6 @@ def autopick_points(self, raw_img_dict, tth_tol=5., eta_tol=5.,
gaussian_2d_int,
[[0., 2.*y0], [0., 2.*x0]],
args=fit_par)
pass
com_angs = np.hstack([
tth_edges[0] + (0.5 + coms[1])*delta_tth,
eta_edges[0] + (0.5 + coms[0])*delta_eta
Expand Down Expand Up @@ -382,14 +379,13 @@ def autopick_points(self, raw_img_dict, tth_tol=5., eta_tol=5.,
#
spot_intensity = np.nan
max_intensity = np.nan
pass
reflInfoList.append([peakId, valid_hkls[:, iRefl],
(spot_intensity, max_intensity),
valid_energy[iRefl],
valid_angs[iRefl, :],
meas_angs[iRefl, :],
meas_xy[iRefl, :]])
pass

reflInfo = np.array(
[tuple(i) for i in reflInfoList],
dtype=reflInfo_dtype)
Expand Down
37 changes: 8 additions & 29 deletions hexrd/fitting/fitpeak.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@
import numpy as np
# from numpy.polynomial import chebyshev

from scipy import integrate
from scipy import ndimage as imgproc
from scipy import optimize
from scipy import integrate, optimize, ndimage as imgproc

from hexrd import constants
from hexrd.imageutil import snip1d
Expand All @@ -54,33 +52,14 @@
alpha0, alpha1, beta0, beta1 = np.r_[14.4, 0., 3.016, -7.94]


def cnst_fit_obj(x, b):
return np.ones_like(x)*b


def cnst_fit_jac(x, b):
return np.vstack([np.ones_like(x)]).T


def lin_fit_obj(x, m, b):
return m*np.asarray(x) + b


def lin_fit_jac(x, m, b):
def lin_fit_jac(x, _m, _b):
Copy link
Collaborator

Choose a reason for hiding this comment

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

Same comment as prior - if _m and _b aren't being used by the function, we shouldn't have them.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Same as above

return np.vstack([x, np.ones_like(x)]).T


def quad_fit_obj(x, a, b, c):
x = np.asarray(x)
return a*x**2 + b*x + c


def quad_fit_jac(x, a, b, c):
x = np.asarray(x)
return a*x**2 + b*x + c
Copy link
Collaborator

Choose a reason for hiding this comment

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

Are we sure this is the incorrect return? The return that's staying doesn't seem to include a, b, or c.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Not sure, but it is actually a matrix which seems to make more sense. Doesn't affect the test cases which is unfortunate, so I couldn't tell.

return np.vstack([x**2, x, np.ones_like(x)]).T


def _amplitude_guess(x, x0, y, fwhm):
pt_l = np.argmin(np.abs(x - (x0 - 0.5*fwhm)))
pt_h = np.argmin(np.abs(x - (x0 + 0.5*fwhm)))
Expand Down Expand Up @@ -198,13 +177,13 @@ def fit_pk_parms_1d(p0, x, f, pktype='pvoigt'):
weight = np.max(f)*10. # hard coded should be changed
fitArgs = (x, f, pktype)
if pktype == 'gaussian':
p, outflag = optimize.leastsq(
p, _ = optimize.leastsq(
fit_pk_obj_1d, p0,
args=fitArgs, Dfun=eval_pk_deriv_1d,
ftol=ftol, xtol=xtol
)
elif pktype == 'lorentzian':
p, outflag = optimize.leastsq(
p, _ = optimize.leastsq(
fit_pk_obj_1d, p0,
args=fitArgs, Dfun=eval_pk_deriv_1d,
ftol=ftol, xtol=xtol
Expand All @@ -214,7 +193,7 @@ def fit_pk_parms_1d(p0, x, f, pktype='pvoigt'):
ub = [p0[0]*2.0, np.max(x), 4.*p0[2], 1., 2.*p0[4], None]

fitArgs = (x, f, pktype, weight, lb, ub)
p, outflag = optimize.leastsq(
p, _ = optimize.leastsq(
fit_pk_obj_1d_bnded, p0,
args=fitArgs,
ftol=ftol, xtol=xtol
Expand All @@ -223,13 +202,13 @@ def fit_pk_parms_1d(p0, x, f, pktype='pvoigt'):
lb = [p0[0]*0.5, np.min(x), 0., 0., 0., 0., 0., None]
ub = [p0[0]*2.0, np.max(x), 4.*p0[2], 4.*p0[2], 1., 1., 2.*p0[4], None]
fitArgs = (x, f, pktype, weight, lb, ub)
p, outflag = optimize.leastsq(
p, _ = optimize.leastsq(
fit_pk_obj_1d_bnded, p0,
args=fitArgs,
ftol=ftol, xtol=xtol
)
elif pktype == 'tanh_stepdown':
p, outflag = optimize.leastsq(
p, _ = optimize.leastsq(
fit_pk_obj_1d, p0,
args=fitArgs,
ftol=ftol, xtol=xtol)
Expand Down Expand Up @@ -403,7 +382,7 @@ def estimate_mpk_parms_1d(
p0tmp_ub = np.zeros([num_pks, npp])

# case processing
# !!! used to use (f[pt] - min_val) for ampl
# !!! used to use (f[pt] - min_val) for amplitude guess
if pktype == 'gaussian' or pktype == 'lorentzian':
# x is just 2theta values
# make guess for the initital parameters
Expand Down
4 changes: 1 addition & 3 deletions hexrd/fitting/grains.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,6 @@ def objFuncFitGrain(gFit, gFull, gFlag,
meas_omes = meas_xyo[:, 2]
xy_unwarped = panel.distortion.apply(meas_xyo[:, :2])
meas_xyo = np.vstack([xy_unwarped.T, meas_omes]).T
pass

# append to meas_omes
meas_xyo_all.append(meas_xyo)
Expand All @@ -234,7 +233,7 @@ def objFuncFitGrain(gFit, gFull, gFlag,
gHat_c = mutil.unitVector(np.dot(rMat_c.T, gVec_s))

# !!!: check that this operates on UNWARPED xy
match_omes, calc_omes = matchOmegas(
_, calc_omes = matchOmegas(
meas_xyo, hkls, chi, rMat_c, bMat, wavelength,
vInv=vInv_s, beamVec=bVec, etaVec=eVec,
omePeriod=omePeriod)
Expand All @@ -251,7 +250,6 @@ def objFuncFitGrain(gFit, gFull, gFlag,

# append to xy dict
calc_xy_dict[det_key] = calc_xy
pass

# stack results to concatenated arrays
calc_omes_all = np.hstack([calc_omes_dict[k] for k in det_keys_ordered])
Expand Down
2 changes: 1 addition & 1 deletion hexrd/imageutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def fast_snip1d(y, w=4, numiter=2):
zfull = _scale_image_snip(y, min_val, invert=False)
for k, z in enumerate(zfull):
b = z
for i in range(numiter):
for _ in range(numiter):
for p in range(w, 0, -1):
kernel = np.zeros(p*2 + 1)
kernel[0] = 0.5
Expand Down
15 changes: 7 additions & 8 deletions hexrd/material/crystallography.py
Original file line number Diff line number Diff line change
Expand Up @@ -1383,14 +1383,13 @@ def getHKLs(self, *hkl_ids, **kwargs):
"""
# kwarg parsing
opts = dict(asStr=False, thisTTh=None, allHKLs=False)
if len(kwargs) > 0:
# check keys
for k, v in kwargs.items():
if k not in opts:
raise TypeError(
f"getHKLs() got an unexpected keyword argument '{k}'"
)
opts.update(kwargs)
# check keys
for k in kwargs.keys():
if k not in opts:
raise TypeError(
f"getHKLs() got an unexpected keyword argument '{k}'"
)
opts.update(kwargs)

hkls = []
if len(hkl_ids) == 0:
Expand Down
57 changes: 32 additions & 25 deletions hexrd/nf_config/experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,35 +31,42 @@ def max_tth(self):

@property
def comp_thresh(self):
key = 'experiment:comp_thresh'
temp = self._cfg.get(key, None)
if temp is None:
return temp
elif np.logical_and(temp <= 1.0, temp > 0.0):
return temp
else:
raise RuntimeError('comp_thresh must be None or a number between 0 and 1')

temp = self._cfg.get('experiment:comp_thresh')
if temp is not None and np.any(
np.logical_or(temp > 1.0, temp <= 0.0)
):
raise RuntimeError(
'comp_thresh must be None or a number between 0 and 1'
)

return temp

@property
def chi2_thresh(self):
key = 'experiment:chi2_thresh'
temp = self._cfg.get(key, None)
if temp is None:
return temp
elif np.logical_and(temp <= 1.0, temp > 0.0):
return temp
else:
raise RuntimeError('chi2_thresh must be None or a number between 0 and 1')
temp = self._cfg.get('experiment:chi2_thresh')
if temp is not None and np.any(
np.logical_or(temp > 1.0, temp <= 0.0)
):
raise RuntimeError(
'chi2_thresh must be None or a number between 0 and 1'
)

return temp


@property
def misorientation(self):
key = self._cfg.get('experiment:misorientation:use_misorientation')
if key is True:
parms = dict(misorientation_bnd='experiment:bnd',
misorientation_spacing='experiment:spacing')
return parms
else:
parms = dict(misorientation_bnd=None,
misorientation_spacing=None) #won't look at spacing if bnd is 0
return parms
if key not in [True, False, None]:
raise ValueError(
'use_misorientation must be of type bool'
)
if key:
return {
'misorientation_bnd': 'experiment:bnd',
'misorientation_spacing': 'experiment:spacing',
}
return {
'misorientation_bnd': None,
'misorientation_spacing': None,
}
Loading
Loading