Skip to content

Commit

Permalink
apply stricter style
Browse files Browse the repository at this point in the history
  • Loading branch information
weaverba137 committed Jan 8, 2025
1 parent c4e7101 commit 008d726
Show file tree
Hide file tree
Showing 14 changed files with 186 additions and 132 deletions.
10 changes: 5 additions & 5 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,18 @@ jobs:
os: [ubuntu-latest]
python-version: ['3.11', '3.12']
numpy-version: ['<2.0', '<2.1', '<2.2', '<3']
astropy-version: ['<6.1', '<7.0'] # , '<7.1'] 7 has an IERS issue
astropy-version: ['<6.1', '<7.0'] # , '<7.1'] 7 has an IERS issue
include:
# Close to current NERSC configuration.
- os: ubuntu-latest
python-version: '3.10'
numpy-version: '<1.23'
astropy-version: '<6.1'
# Stable, yet close to bleeding-edge.
# - os: ubuntu-latest
# python-version: '3.13'
# numpy-version: '<3'
# astropy-version: '<7.1'
- os: ubuntu-latest
python-version: '3.13'
numpy-version: '<3'
astropy-version: '<7.0' # not <7.1 yet, see above

steps:
- name: Checkout code
Expand Down
1 change: 1 addition & 0 deletions doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ If you want to work with the dust utilities in :mod:`desiutil.dust`, you will
need:

* `SciPy <https://scipy.org>`_
* `speclite <https://speclite.readthedocs.io/en/latest/>`_

Contents
========
Expand Down
6 changes: 4 additions & 2 deletions py/desiutil/annotate.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,11 +465,13 @@ def _options():
parser.add_argument('-D', '--disable-comments', action='store_true', dest='disable_comments',
help='Do not add comments, even if they are defined in one of the inputs.')
parser.add_argument('-e', '--extension', dest='extension', action='store', metavar='EXT', default='1',
help="Update FITS extension EXT, which can be a number or an EXTNAME. If not specified, HDU 1 will be updated, which is standard for simple binary tables.")
help=("Update FITS extension EXT, which can be a number or an EXTNAME. " +
"If not specified, HDU 1 will be updated, which is standard for simple binary tables."))
parser.add_argument('-o', '--overwrite', dest='overwrite', action='store_true',
help='Overwrite the input FITS file.')
parser.add_argument('-T', '--truncate-comments', dest='truncate', action='store_true',
help='Allow any long comments to be truncated when written out. Without this option, long comments will raise an error.')
help=('Allow any long comments to be truncated when written out. ' +
'Without this option, long comments will raise an error.'))
parser.add_argument('-u', '--units', action='store', dest='units', metavar='UNITS',
help="UNITS should have the form COLUMN='unit':COLUMN='unit'.")
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
Expand Down
20 changes: 8 additions & 12 deletions py/desiutil/depend.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,14 @@
#
# default possible dependencies to check in add_dependencies()
#
possible_dependencies = [
'numpy', 'scipy', 'astropy', 'yaml', 'matplotlib',
'requests', 'fitsio', 'h5py', 'mpi4py', 'psycopg2', 'healpy',
'desiutil', 'desispec', 'desitarget', 'desimodel', 'desisim', 'desisurvey',
'specter', 'speclite', 'specsim', 'surveysim', 'redrock', 'desimeter',
'fiberassign', 'gpu_specter',
]
possible_envvars = [
'DESI_ROOT', 'DESI_SPECTRO_DATA', 'DESI_SPECTRO_REDUX', 'SPECPROD',
'DESI_SPECTRO_CALIB', 'DESI_BASIS_TEMPLATES',
'DESI_TARGET', 'DESIMODEL',
]
possible_dependencies = ['numpy', 'scipy', 'astropy', 'yaml', 'matplotlib',
'requests', 'fitsio', 'h5py', 'mpi4py', 'psycopg2', 'healpy',
'desiutil', 'desispec', 'desitarget', 'desimodel', 'desisim', 'desisurvey',
'specter', 'speclite', 'specsim', 'surveysim', 'redrock', 'desimeter',
'fiberassign', 'gpu_specter',]
possible_envvars = ['DESI_ROOT', 'DESI_SPECTRO_DATA', 'DESI_SPECTRO_REDUX', 'SPECPROD',
'DESI_SPECTRO_CALIB', 'DESI_BASIS_TEMPLATES',
'DESI_TARGET', 'DESIMODEL',]


def setdep(header, name, version):
Expand Down
21 changes: 10 additions & 11 deletions py/desiutil/dust.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,12 +526,12 @@ def __init__(self, fname, scaling):
self.lam_scal = header['LAM_SCAL']
self.sign = header['LAM_NSGP'] # north = 1, south = -1

def ebv(self, l, b, interpolate):
def ebv(self, gal_l, gal_b, interpolate):
"""Project Galactic longitude/latitude to lambert pixels (See SFD98).
Parameters
----------
l, b : :class:`numpy.ndarray`
gal_l, gal_b : :class:`numpy.ndarray`
Galactic longitude and latitude.
interpolate : :class:`bool`
If ``True`` use bilinear interpolation to obtain values.
Expand All @@ -542,11 +542,11 @@ def ebv(self, l, b, interpolate):
Reddening values.
"""
x = (self.crpix1 - 1.0 +
self.lam_scal * np.cos(l) *
np.sqrt(1.0 - self.sign * np.sin(b)))
self.lam_scal * np.cos(gal_l) *
np.sqrt(1.0 - self.sign * np.sin(gal_b)))
y = (self.crpix2 - 1.0 -
self.sign * self.lam_scal * np.sin(l) *
np.sqrt(1.0 - self.sign * np.sin(b)))
self.sign * self.lam_scal * np.sin(gal_l) *
np.sqrt(1.0 - self.sign * np.sin(gal_b)))

# Get map values at these pixel coordinates.
if interpolate:
Expand Down Expand Up @@ -652,10 +652,7 @@ def ebv(self, *args, **kwargs):
frame = 'fk5'

# compatibility: treat single argument 2-tuple as (RA, Dec)
if (
(len(args) == 1) and (type(args[0]) is tuple)
and (len(args[0]) == 2)
):
if (len(args) == 1) and (type(args[0]) is tuple) and (len(args[0]) == 2):
args = args[0]

if len(args) == 1:
Expand Down Expand Up @@ -814,7 +811,9 @@ def _main():
import matplotlib.pyplot as plt

parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="Runs and displays a comparison between tabulated values of total to selective extinction ratios and values obtained with synthetic mags.")
description=("Runs and displays a comparison between " +
"tabulated values of total to selective extinction " +
"ratios and values obtained with synthetic mags."))
args = parser.parse_args()

plt.figure("reddening")
Expand Down
3 changes: 2 additions & 1 deletion py/desiutil/iers.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ def freeze_iers(name='iers_frozen.ecsv', ignore_warnings=True):
# to prevent any IERSRangeError being raised.
class IERS_Frozen(astropy.utils.iers.IERS_B):
def _check_interpolate_indices(self, indices_orig, indices_clipped,
max_input_mjd): pass
max_input_mjd):
pass

# Create and register an instance of this class from the table.
iers = IERS_Frozen(table)
Expand Down
11 changes: 4 additions & 7 deletions py/desiutil/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@
'tilepicker': 'https://github.com/desihub/tilepicker',
'timedomain': 'https://github.com/desihub/timedomain',
'plate_layout': 'https://desi.lbl.gov/svn/code/focalplane/plate_layout',
'positioner_control':
'https://desi.lbl.gov/svn/code/focalplane/positioner_control',
}
'positioner_control': 'https://desi.lbl.gov/svn/code/focalplane/positioner_control'}


#
Expand Down Expand Up @@ -109,8 +107,8 @@ def dependencies(modulefile):
raise ValueError("Modulefile {0} does not exist!".format(modulefile))
with open(modulefile) as m:
lines = m.readlines()
return [l.strip().split()[2] for l in lines if
l.strip().startswith('module load')]
return [ln.strip().split()[2] for ln in lines if
ln.strip().startswith('module load')]


class DesiInstallException(Exception):
Expand Down Expand Up @@ -605,8 +603,7 @@ def set_install_dir(self):
if self.options.root is None and self.nersc is not None:
self.options.root = self.default_nersc_dir()

if ((self.options.root is None or not os.path.isdir(self.options.root))
and not self.options.test):
if ((self.options.root is None or not os.path.isdir(self.options.root)) and not self.options.test):
message = "Root install directory is missing or not set."
self.log.critical(message)
raise DesiInstallException(message)
Expand Down
22 changes: 10 additions & 12 deletions py/desiutil/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,18 +183,16 @@ def configure_module(product, version, product_root, working_dir=None, dev=False
"""
if working_dir is None:
working_dir = os.getcwd()
module_keywords = {
'name': product,
'version': version,
'product_root': product_root,
'needs_bin': '# ',
'needs_python': '# ',
'needs_trunk_py': '# ',
'trunk_py_dir': '/py',
'needs_ld_lib': '# ',
'needs_idl': '# ',
'pyversion': "python{0:d}.{1:d}".format(*sys.version_info)
}
module_keywords = {'name': product,
'version': version,
'product_root': product_root,
'needs_bin': '# ',
'needs_python': '# ',
'needs_trunk_py': '# ',
'trunk_py_dir': '/py',
'needs_ld_lib': '# ',
'needs_idl': '# ',
'pyversion': "python{0:d}.{1:d}".format(*sys.version_info)}
if os.path.isdir(os.path.join(working_dir, 'bin')):
module_keywords['needs_bin'] = ''
if os.path.isdir(os.path.join(working_dir, 'lib')):
Expand Down
10 changes: 6 additions & 4 deletions py/desiutil/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ def plot_slices(x, y, x_lo, x_hi, y_cut, num_slices=5, min_count=100, axis=None,
axis.scatter(x, y, s=15, marker='.', lw=0, color='b', alpha=0.5, zorder=1)

# Plot quantiles in slices with enough fits.
stepify = lambda y: np.vstack([y, y]).transpose().flatten()
def stepify(y):
return np.vstack([y, y]).transpose().flatten()

y_m2 = stepify(limits[:, 0])
y_m1 = stepify(limits[:, 1])
y_med = stepify(limits[:, 2])
Expand Down Expand Up @@ -437,7 +439,7 @@ def projection_dec(self, dec):
#
base_tick_labels = np.array([150, 120, 90, 60, 30, 0, 330, 300, 270, 240, 210])
base_tick_labels = np.remainder(base_tick_labels+360+ra_center, 360)
tick_labels = np.array(['{0}°'.format(l) for l in base_tick_labels])
tick_labels = np.array(['{0}°'.format(lab) for lab in base_tick_labels])
#
# Galactic plane.
#
Expand Down Expand Up @@ -475,8 +477,8 @@ def projection_dec(self, dec):
# Set RA labels.
#
labels = ax.get_xticklabels()
for l, item in enumerate(labels):
item.set_text(tick_labels[l])
for i, item in enumerate(labels):
item.set_text(tick_labels[i])
ax.set_xticklabels(labels)
#
# Set axis labels.
Expand Down
18 changes: 10 additions & 8 deletions py/desiutil/test/test_annotate.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,30 +100,32 @@ def test_find_key_name(self):
def test_validate_unit(self):
"""Test function to validate units.
"""
m = "'ergs' did not parse as fits unit: At col 0, Unit 'ergs' not supported by the FITS standard. Did you mean erg?"
d = "'1/deg^2' did not parse as fits unit: Numeric factor not supported by FITS"
f = "'1/nanomaggy^2' did not parse as fits unit: Numeric factor not supported by FITS"
l = " If this is meant to be a custom unit, define it with 'u.def_unit'. To have it recognized inside a file reader or other code, enable it with 'u.add_enabled_units'. For details, see https://docs.astropy.org/en/latest/units/combining_and_defining.html"
erg = "'ergs' did not parse as fits unit: At col 0, Unit 'ergs' not supported by the FITS standard. Did you mean erg?"
deg = "'1/deg^2' did not parse as fits unit: Numeric factor not supported by FITS"
mag = "'1/nanomaggy^2' did not parse as fits unit: Numeric factor not supported by FITS"
cust_unit = (" If this is meant to be a custom unit, define it with 'u.def_unit'. " +
"To have it recognized inside a file reader or other code, enable it with " +
"'u.add_enabled_units'. For details, see https://docs.astropy.org/en/latest/units/combining_and_defining.html")
c = validate_unit(None)
self.assertIsNone(c)
c = validate_unit('erg')
self.assertIsNone(c)
with self.assertWarns(FITSUnitWarning) as w:
c = validate_unit('ergs', error=False)
self.assertEqual(str(w.warning), m + l)
self.assertEqual(str(w.warning), erg + cust_unit)
self.assertIsNone(c)
with self.assertWarns(FITSUnitWarning) as w:
c = validate_unit('1/deg^2')
self.assertEqual(str(w.warning), d + l)
self.assertEqual(str(w.warning), deg + cust_unit)
self.assertIsNone(c)
c = validate_unit('nanomaggies', error=True)
self.assertEqual(c, "'nanomaggies'")
with self.assertRaises(ValueError) as e:
c = validate_unit('ergs', error=True)
self.assertEqual(str(e.exception), m + l)
self.assertEqual(str(e.exception), erg + cust_unit)
with self.assertRaises(ValueError) as e:
c = validate_unit('1/nanomaggy^2', error=True)
self.assertEqual(str(e.exception), f + l)
self.assertEqual(str(e.exception), mag + cust_unit)

@patch('desiutil.annotate.get_logger')
def test_check_comment_length(self, mock_log):
Expand Down
Loading

0 comments on commit 008d726

Please sign in to comment.